gpt4 book ai didi

javascript - 从主干路由器访问主干 View 中的变量

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

我的路由器

var AppRouter = Backbone.Router.extend({
routes: {
':*':'home',
'home' : 'home',
'home/:a' : 'home',
'*whatever' : '404'

},
home: function (a) {
document.title = siteTitle + ' - Home';
homePage = new HomePage;
homePage.render(a);
},
404: function(){
document.title = siteTitle + ' - 404';
fofPage = new FoFPage;
fofPage.render();
}

});

我的主页 View

var HomePage = Backbone.View.extend({
initialize: function (options) {
_.bindAll(this, 'beforeRender', 'render', 'afterRender');
var _this = this;
this.render = _.wrap(this.render, function (render) {
_this.beforeRender();
render();
_this.afterRender();
return _this;
});
},

beforeRender: function () {
console.log('beforeRender');
},

el: $('#indexcontent'),

template: _.template(homeHTML, {}),

render: function (a) {
(a == null) ? Backbone.history.navigate('home'): Backbone.history.navigate('home/' + a);
console.log('Passed parameter is ' + a);
this.$el.html(this.template);

},

afterRender: function () {
$('pre code').each(function (i, block) {
hljs.highlightBlock(block);
});
console.log('afterRender');
}
});

我正在尝试从路由器捕获该变量a以进行查看。但它在我的控制台中显示未定义。我尝试在初始化中摆弄变量 options 但没有运气。谢谢

最佳答案

当您找到答案时,我将解释为什么您的初始代码不起作用,甚至更多。

为什么传递给 render 不起作用?

因为您要使用包装版本覆盖 initialize 函数中的 render 函数,使用 underscore's wrap功能。

它可以工作,但你需要在包装时考虑参数:

this.render = _.wrap(this.render, function(render, a) {
this.beforeRender();
render.call(this, a); // here, pass the argument
this.afterRender();
return this;
});

另请注意,您不需要 var _this = this,因为您只是替换成员函数,并且在调用时会自动应用上下文。 _.bindAll 也是如此,这里没用。

更简单的方法

这种包装是不必要的,它只是使 HomePage View 变得复杂,没有任何好处或添加功能。

您唯一需要的东西:

var HomePage = Backbone.View.extend({
el: $('#indexcontent'),

您可以忽略选项参数({})

    template: _.template(homeHTML),

initialize: function(options) {

如果您想传递选项进行初始化,请使用以下模式之一:

        this.options = options || {}; // make sure it's an object.

或者,更好的是,确保它是具有默认值的对象的副本

        this.options = _.extend({
route: "default-value"
}, options);
},

beforeRender: function() {
console.log('beforeRender');
},

render: function(route) {
this.beforeRender();

在路由器中做重定向,这是他的职责。

        // (a == null) ? Backbone.history.navigate('home'): Backbone.history.navigate('home/' + a);

console.log('Passed parameter is ' + route || this.options.route);

underscore's _.template function 返回一个函数,因此您需要调用它。

        this.$el.html(this.template());

this.afterRender();
return this;
},

afterRender: function() {

避免使用全局 jQuery 函数,更喜欢使用 this.$(selector) 将搜索范围限定为 View 元素及其子元素。

        this.$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
console.log('afterRender');
}
});

关于javascript - 从主干路由器访问主干 View 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444395/

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