2013-05-08 47 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

相關問題