gpt4 book ai didi

javascript - Backbone.js 在 View 提交事件上执行模型获取

转载 作者:行者123 更新时间:2023-11-28 08:20:24 25 4
gpt4 key购买 nike

在 Backbone.View 中,我有一个表单。提交后,我想执行 model.fetch()。我该如何以正确的 Backbone.js MVC 方式解决这个问题?

方法 A,看起来风格很糟糕。

//in my Backbone.View:
events: {'submit form#frm-destination': 'setDestination'},
setDestination: function(event){
event.preventDefault();
var destination = $('#destination').val();
this.model.fetch({
data : {
address : destination,
}
});
},

方法B: 有没有办法编写一个路由器并让它监听我的 View 的提交事件?

  ///in my Backbone.Router
this.listenTo(this.view, 'submit', this.onFormSubmit);
...
onFormSubmit: function(){
console.log('caught button push!');
},

不幸的是,上面的方法不起作用。

最佳答案

我自己找到了解决方案:

我定义了一个新模型:

var DestinationModel = Backbone.Model.extend({});

在我的路由器中,我有:

intialize: function(){
_.bindAll(this,'onDestinationChange');
this.modelToFetchModel = newMyModel();

this.destinationModel = new DestinationModel();
this.destinationView = new DestinationView({ model : this.destinationModel });
this.listenTo(this.destinationModel, 'change', this.onManualDestination);
},
onDestinationChange: function(model){
this.modelToFetchModel.fetch({ data : { address : model.get('destination') } });
}

我的 View 如下所示:

var DestinationView = Backbone.View.extend({
events: {'submit form#frm-destination': 'setDestination'},
initialize: function(){
_.bindAll(this,'setDestination');
}
setDestination: function(event){
event.preventDefault();
var destination = $('#destination').val();
this.model.set('address',destination);
}
});

关于javascript - Backbone.js 在 View 提交事件上执行模型获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com