开发者

Can't grok the process of updating UI on model change

I have a collection of models. When a model changes it triggers a change event on the collection. I watch for the collection change event and then I update the UI.

How should I go about updating the UI? Don't I need to know what models are new, so I can append, and what already exist, so I can update?

One of the reason I feel I need this granularity is because there's an animation transition, so I need to relate every model to it's previous state. Does backbone help with t开发者_Go百科his or should I just build this on my own?


to know which models are new, listen to the collection's "add" event. then you can render the individual item.


MyView = Backbone.View.extend({

  initialize: function(){
    _.bindAll(this, "renderItem");
    this.collection.bind("add", this.renderItem);
  },

  renderItem: function(item){
    // render the new item here
  },

  render: function(){
    this.collection.each(this.renderItem);
  }
});

in this example, rendering the collection works the same as rendering an individual item - it calls the same renderItem method that the "add" event calls.

to handle the scenario where you have a sorted list... you'll have to do some logic in your renderItem method to figure out the location of the item. something like this maybe (untested code... just an idea):


MyView = Backbone.View.extend({

  initialize: function(){
    _.bindAll(this, "renderItem");
    this.collection.bind("add", this.renderItem);
  },

  renderItem: function(item){
    var itemView = new ItemView({model: item});
    itemView.render();
    return itemView;
  },

  render: function(){
    this.collection.each(function(item){
      var itemView = renderItem(item);
      var itemIndex = item.get("index");
      var previousItem = this.$(".myList")[itemIndex];
      $(itemView.el).insertAfter($(previousItem));
    });
  }
});

this code assumes you have an index attribute on your models to know the order that the models are supposed to be in.

also note that there's a high likelihood that this code won't execute as-is, since i haven't tested it out. but it should give you an idea of the code you'll want to write.


You don't need to go through the collection if the model changes. Simple render a sub view for each model and in which you can handle the change event.

Imagine you have the following structure:

Collection: Tasks
Model:      Task

And two views:

Tasks view  (main view)
Task view   (sub view)

In the #render method of the Tasks view you render e.g. a <ul> element which will hold your tasks (sub views). Then you iterate through all your collection's models and create a Task view for each, passing the model and appending it's el to your main views <ul>. Within your Task view you bind the #render method to the models change event and each Task view will take care of itself. — Am I making sense?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜