【问题标题】:reseting a collection on change model event?重置更改模型事件的集合?
【发布时间】:2012-08-16 19:08:23
【问题描述】:

我有这个主干脚本,它有一个视图和一个充当控制器的模型,以及一个从服务器url: '/search/:term' 获取数据的集合。

    var Items = Backbone.Collection.extend({
          initialize: function(terms){
            this.fetch();
        }
          url: 'search/:term'
    });

   var Controller = Backbone.Model.extend({
       defaults:{
        term: ""
     },
      initialize: function(opts){

        this.on('change:term', function(term){
            console.log(this.get("term"));
          // every time term changes i want to refresh the collection with the new data
          // so it will fetch data from url:'search/ + term'
        });

有人可以帮我解决这个问题吗?谢谢。 } });

【问题讨论】:

  • 您能说明一下您要达到的目标吗?如果你想听一些 dom 事件,你应该使用 Backbone.View。在主干上下文中,视图充当控制器。

标签: javascript model-view-controller backbone.js


【解决方案1】:

在主干上下文中,视图充当控制器(从 mvc 中读取控制器)。你能尝试做这样的事情吗?

YourView = Backbone.View.extend({
  events : { 
    'change #dom-id' : 'handleChange' //function to fire when you change the dom
  },
  initialize: function(){
    this.collection.bind("reset", updateView); //when collection is done, updateView fires
  }, 
  render: function(){
    //do your render logic here, use a template etc.. //initial rendering
  },
  handleChange : function(changeEvent){
    //get value from dom-element, tell the collection to 
    //fetch again with the new term
  },
  updateView : function(){
    //Code that fires when the collection is done fetching 
  }
});

【讨论】:

  • 添加一个函数到你的集合中:search : function(term){ this.url = 'search/'+term; this.fetch(); },
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多