在热毛巾/ Durandal单页应用程序中加载View(激活)的调用函数

时间:2013-05-08 15:15:33

标签: javascript html5 single-page-application durandal hottowel

我正在使用Hot Towel SPA项目,我试图在激活视图时调用简单的js函数。我所看到的是,当调用activate函数时,似乎没有加载该项。

我也尝试将代码放在由其他SO帖子建议的activate调用的初始化函数中。这似乎没有帮助。

那么在Durandal / HotTowel中调用视图加载函数的推荐方法是什么?

home.js(查看模型)

define(['services/logger'], function (logger) {
    var vm = {
        activate: activate,
        title: 'Home'
    };

    return vm;

    function activate() {       
        logger.log('Home View Activated', null, 'home', true);
        return init();
    }

    function init() {
        $("#backBtn").hide();
        console.log($("#myBtn").html()); // returns undefined 
    }
});

home.html(查看)

<section>  
  <div id="myBtn">test</div>
</section>

3 个答案:

答案 0 :(得分:12)

根据Interacting with the DOM的最新Durandal文档,viewAttached已重命名为附加,因此您使用Durandal 2的代码将如下:

define(['services/logger'], function (logger) {
var vm = {
    activate: activate,
    attached: attached
    title: 'Home'
};

return vm;

function activate() {       
    logger.log('Home View Activated', null, 'home', true);
}

function attached(view, parent) {
    $(view).find("#backBtn").hide();
    console.log($(view).find("#myBtn").html()); 
}
});

答案 1 :(得分:9)

当durandal附加一个视图模型时,它会查看viewAttached方法的模型。我在下面修改了你的代码。它应该找到你正在寻找的jQuery元素。

define(['services/logger'], function (logger) {
    var vm = {
        activate: activate,
        viewAttached: viewAttached
        title: 'Home'
    };

    return vm;

    function activate() {       
        logger.log('Home View Activated', null, 'home', true);
    }

    function viewAttached(view) {
        $(view).find("#backBtn").hide();
        console.log($(view).find("#myBtn").html()); 
    }
});

请查看底部的“合成”页面,了解viewAttached的更多信息。 http://durandaljs.com/documentation/Using-Composition.html

答案 2 :(得分:2)

根据Interacting with the DOM的Durandal文档,视图模型有4个回调可以实现,以便与DOM元素进行交互,每个元素都传递一个表示视图的DOMElement

  • getView
  • beforeBind
  • afterBind
  • viewAttached

它指出viewAttached是最常用的钩子。有关每个回调的更详细说明,请参阅文档。您可以在Hooking Lifecycle Callbacks底部的表格中查看完整生命周期。

define(['services/logger'], function (logger) {
    var vm = {
        activate: activate,
        getView: getView,
        beforeBind: beforeBind,
        afterBind: afterBind,
        viewAttached: viewAttached,
        title: 'Home'
    };

    return vm;

    function activate() {       
        logger.log('Home View Activated', null, 'home', true);
        return init();
    }

    function getView(view) {
    }

    function beforeBind(view) {
    }

    function afterBind(view) {
    }

    function viewAttached(view) {
        $("#backBtn").hide();
        console.log($("#myBtn").html()); // returns undefined 
    }
});