我正在嘗試爲中央控制器(實際上是骨幹視圖)定義新的屬性,以使其更加劃分和結構化。我嘗試通過if語句在不同情況下實現我想要實現的渲染,並在這些新屬性中實現每個案例的渲染。但插入替代代碼後,它會使我的應用程序無法工作,從而實現該代碼並評論代碼。定義自定義屬性並在需要時從AMD/Require.js模塊加載其他模塊?
我做了什麼錯事。
另一種我可以想象的模塊化方式是再次有條件地加載不同的AMD/Require.js模型,我用單獨的文件/ s加載並加載它們。但是如何?通過render()內部的require(),或者通過將新的moduleName傳遞給下面的define()的第二個參數。
調用render_app
和
render_login
define([
'jquery',
'ratchet',
'underscore',
'backbone',
'models/login',
'text!templates/login.html',
'text!templates/app.html'
], function($, Ratchet, _, Backbone, LoginModel, LoginTmpl, AppTmpl){
var LoginView = Backbone.View.extend({
el: $("body"),
template_login: _.template(LoginTmpl),
template_app: _.template(AppTmpl),
initialize: function(){
this.model = new LoginModel;
this.listenTo(this.model, 'change', this.render);
this.render();
},
//Replacement code: two attributes:
render_login: function(){
this.$el.html(this.template_app(this.model.toJSON()));
console.log(JSON.stringify(this.model));
return this;
}
},
render_app: function(){
this.$("#content").html(this.template_login(this.model.toJSON()));
console.log(JSON.stringify(this.model));
return this;
},
render: function() {
/*
if (this.model.get('loginp') == true) {
this.$el.html(this.template_app(this.model.toJSON()));
console.log(JSON.stringify(this.model));
return this;
}
*/
/*
else {
this.$("#content").html(this.template_login(this.model.toJSON()));
console.log(JSON.stringify(this.model));
return this;
}
*/
//Replacement code:
if (this.model.get('loginp') == true) {
this.render_app;
} else {
this.render_login;
}
},
events: {
'click #loginbtn' : 'login',
'click #registerbtn' : 'register'
},
login: function(e){
e.preventDefault();
var formData = {};
$('input').each(function(i, el) {
if($(el).val() != '') {
if(el.id === 'username') {
formData[ el.id ] = $(el).val();
} else if(el.id === 'password') {
formData[ el.id ] = $(el).val();
}
}
console.log(i + ": " + $(el).val());
console.log(JSON.stringify(formData));
// Clear input field values
$(el).val('');
});
this.model.save(formData);
}
});
return LoginView;
});
但我發送的代碼有語法錯誤。關閉渲染登錄屬性匿名函數應該只有一個'}'那裏有兩個。 再加上你的回答,還有一件事情,render_app和render_login的名字應該互換。他們的實現有彼此的模板加載。 – 2014-09-30 20:46:40
在您提出問題的初始階段,您已經提到此腳本在更改之前有效。所以我沒有像'}'那樣查找語法錯誤。你的if語句和方法的實現是你特別的問題,你應該決定選擇哪一個,而不是答案編寫者。因此,考慮到這一點,請糾正您的語法結尾邏輯問題,並刪除您添加的答案,因爲實際上它是重複我的。 – 2014-09-30 21:10:25
我的答案是解決問題的方法。謝謝你的回答,但是它不足以讓它工作。當然,在替換我提到的代碼時,我無意中在該位置添加了一個額外的括號,並且這不是代碼中的另一種問題,而是您建議的解決方案。兩者都是語法問題和解決方案。而合乎邏輯的問題是另一個可以作爲另一個答案的問題,但又不如你的答案和我自己的兩個答案一樣完整。甚至更多,你的回答在我的回答中被提及,屬於不屬於我的。 – 2014-09-30 21:26:11