0
我想用一個文件的.on方法來偵聽另一個文件,如果發生更改,我希望它觸發一個新視圖的渲染。這是我的嘗試,甚至將某些東西打印到控制檯,它不起作用。如何連接來自不同文件的事件? Javascript /骨幹
這是我的路由器文件:
define([
'jquery',
'underscore',
'backbone',
'views/page',
'models/search',
'views/search',
'text!templates/search.html'
], function($, _, Backbone, PageV, SearchM, SearchV, SearchT) {
var vent = _.extend({}, Backbone.Events);
var AppRouter = Backbone.Router.extend ({
routes: {
'page/:id': 'showPage',
's': 'showView'
}
});
var initialize = function() {
var app_router
app_router = new AppRouter;
app_router.on('route:showPage', function (id) {
var page = new PageV();
page.render(id);
});
**app_router.on('route:showView', function() {
var searchM = new SearchM({vent: vent});
var search = new SearchV({model: searchM, vent: vent}); //
$('#Sirius').html(SearchT);
search.render();
vent.on('nextPage', this.printCons);
function printCons() {
console.log('printing from listening')
};**
});
Backbone.history.start();
};
return {
initialize: initialize
};
});
這是搜索視圖文件,所呈現的,但不是要求在路由器中的console.log功能(即羣星環繞)
define([
'jquery',
'underscore',
'backbone',
'models/search',
'text!templates/search.html',
], function($, _, Backbone, SearchM, SearchT){
var vent = _.extend({}, Backbone.Events);
var Search = Backbone.View.extend({
el: $("#Sirius"),
events: {
'submit #searchMusic': 'search'
},
search: function (e) {
console.log('searching...');
e.preventDefault();
var _this, that;
_this = this;
that = this.model;
//post instance to the server with the following input fields
this.model.save({
channel: $('#channel').val(),
week: $('#week').val(),
year: $('#year').val(),
filter: $('#filter').val()
},{success: storeMusic });
function storeMusic (that, response, options) {
console.log('store');
//create new instance of the localStorage with the key name
_this.model.localStorage = new Backbone.LocalStorage("music");
_this.clearLocalStorage(_this);
_this.saveToLocalStorage(response, _this);
};
},
clearLocalStorage: function (_this) {
console.log('clear');
//removes the items of the localStorage
_this.model.localStorage._clear();
//pops out the first key in the records
_this.model.localStorage.records.shift();
},
saveToLocalStorage: function (response, _this) {
console.log('save');
_this.model.save({music: response}, {success: _this.nextPage});
},
nextPage: function (_this, response, options) {
console.log('entered next page');
vent.trigger('nextPage', this.model)
}
});
return Search;
});
該功能正在被調用,一切工作正常,我正在努力讓事件在路由器端聽到,所以我可以讓用戶導航到另一個頁面後點擊提交按鈕,並返回的響應成功存儲本地存儲。 nextPage函數確實被調用,但我認爲我沒有正確實現vent.trigger或.on ...我在路由器和視圖中都調用它(var vent = ...)
雅我得到了它在結束工作,我做了類似的事情,但是,是兩個不同的變量是一個問題 – Lion789
較好,requirejs,我確實維護一個全局模型實例,它可以作爲依賴加載到任何模塊,我將所有的util方法和全局變量鏈接到那裏。這有助於我在視圖層面監聽全局模型更改。 –