English 中文(简体)
Backbone.js: 以不同数据更新收藏
原标题:Backbone.js: Update Collection with different data

我有一套模型的后骨集, 其页面载量中的数据 与当它被取出时不同。

例如,页面载荷上的属性是:

[{ name:  cat , color:  yellow  },
 { name:  dog , color:  brown  },
 { name:  fish , color:  orange  }]

然后,在抓取 () (或者在页面使用期间从服务器上更新) 时, 数据看起来像 :

[{ name:  cat , current: 5, total: 100 },
 { name:  dog , current: 6, total: 50 },
 { name:  fish , current:7, total: 25 }]

在保留旧数据的同时, 我如何才能用新数据更新 Backbone 收藏? ID 不从服务器上指定( 保证名称为独一) 。

最佳回答

最后,我接着做了这个。这将更新现有模型的属性,同时删除未进入的模型,并添加新的模型。

Backbone.Collection.prototype.update = function(col_in){  
  var self = this,
      new_models = [];

  _(col_in).each(function(mod_in) {
    var new_model = self._prepareModel(mod_in),
        mod = self.get(new_model.id);
    if (mod) { 
      new_models.push(mod.set(mod_in, {silent:true}));
    } else { 
      new_models.push(mod_in);
    }
  });

  this.reset(new_models);
};

请注意使用 非常重要,这样就可以通过在 Backbone 模型对象中使用的“ id” 属性来识别模型。

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签