Backbone: multiple View Models for the same model

前端 未结 4 1217
暗喜
暗喜 2021-02-05 23:25

Newbie backbone question:

Context: Building a shopping list with backbone

I have a model class called with name, description and tags (array) properties. I would

相关标签:
4条回答
  • 2021-02-05 23:32

    After a little research, I found Collection.Parse method that seems to be right place for transforming the response after a fetch() operation. Looks like I will need a new set model, collection and view objects. This is how I implemented the parse function in my collection object. Tested successfully in Chrome. Feel free to suggest improvements

        <snip>
        parse: function(response) {
    
            var items = response; //the raw item model returned from localStorage  
            var tagNameItemCount = [];
            var selectedTags = ["Tag1", "Tag2", "Tag3"];
            for(i = 0; i < selectedTags.length; i++){
                var currentTagName = selectedTags[i];
                var currentItemCount = this.getItemsCountByTagName(currentTagName, items);
                tagNameItemCount.push({tagName: currentTagName, tagCount: currentItemCount});
            }
    
            return tagNameItemCount;
    
    
    
           },
    getItemsCountByTagName: function (tagName, items) {
                            var taggedItems = _.filter(items, function(item){ return _.include(item.tags, tagName); });
                            return taggedItems.length;
                           },
    
         </snip>
    
    0 讨论(0)
  • 2021-02-05 23:34

    I'm pretty new to Backbone.js myself, so take this answer with a grain of salt, but I think ... you just make the second view. The whole point of de-coupling models and views is to make it so that you don't need to do anything to the models if all you want to do is do something different with your views.

    So, I think you just need to create YourView2, tell it to use the same model as YourView1 and you should be in business.

    0 讨论(0)
  • 2021-02-05 23:38

    @machineghost is right on; The models are totally decoupled from the views so you can make as many views attached to the same model as you please. You could also extend a view, if they have logic or attributes you would like to share. When I use Backbone I often find myself extending a parent view just to override the render function, or to provide a different template.

    First view

    ShoppingCartView = Backbone.View.extend({
      model: ShoppingCart
      ...
    });
    

    Second independent view

    CheckoutView = Backbone.View.extend({
      model: ShoppingCart
      ...
    });
    

    Second view extends first

    CheckoutView = ShoppingCartView.extend({ 
      template: a_different_template // syntax depends on your templating framework
      ... 
    });
    
    0 讨论(0)
  • 2021-02-05 23:48

    Paul Yoder from Backbone.js google group provided the solution. You can view it here

    0 讨论(0)
提交回复
热议问题