2013-05-08 13 views
5

我正在使用Hot Towel SPA项目我试图在激活视图时调用简单的js函数。我所看到的是该项目在调用激活功能时似乎没有加载。在Hot Towel/Durandal单页面查看加载(激活)时调用函数应用程序

我也尝试把代码放在一个初始化函数中,按照其他SO帖子上的建议激活。这似乎没有帮助。

那么在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> 

回答

9

当迪朗达尔附着它看起来在该模型用于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()); 
    } 
}); 

看一看组合页面底部多一点关于viewAttachedhttp://durandaljs.com/documentation/Using-Composition.html

+1

还检查了[与DOM交互(HTTP ://durandaljs.com/documentation/Interacting-with-the-DOM/)文档页面。 – blachniet 2013-05-08 16:11:44

+0

美丽。感谢你们俩! – 2013-05-08 18:13:08

+1

由于Durandal的变化,此答案不再正确。 viewAttached函数不会再被调用。此外,该文档的链接被破坏。请更新您的答案。 – Mtz 2013-10-08 10:11:46

2

根据在Interacting with the DOM的迪朗达尔文档,视图模型具有4个回调它们可以以与DOM elments交互,实现其中的每一个通过一个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 
    } 
}); 
12

据当时Interacting with the DOM最新迪朗达尔文档,viewAttached改名为连接,让您使用迪朗达尔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()); 
} 
}); 
+0

这是很好的更新的答案杜兰达2.0,因为你说得很对,其他人适合2.0之前 – LearningNeverEnds 2013-12-31 18:33:53

相关问题