2015-06-16 11 views
0

我使用mustache模板和ajax將一些內容呈現到我的頁面中。然後我想使用另一個函數(componentLoaded)與某些元素進行交互(根據頁面位置隱藏它們)。如何使用jQuery訪問使用Mustache呈現到頁面中的元素

顯然這個函數需要在頁面上渲染項目之後運行,但是這是如何完成的?我想用我的Ajax調用的承諾延期對象,但是這似乎並沒有工作:

var template = null; 

//Get Template 
function getTemplate() { 
    return $.get('mustache/components/block.mustache', function(response) { 
     template = response; 
    }).then(renderComponent()); 
} 

//Render Template 
function renderComponent() { 
    // Get Data 
    return $.ajax('JSON/testData.json',{ 
     dataType: 'json', 
     success: function(data) { 
      if(template != null) { 
       for(var i = 0; i < data.blocks.length; i++) { 

        renderTemplate(template, data.blocks[i], $('#container')); 
       } 
      } 
      else { 
       console.error('Error: Template failed to load'); 
      } 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      console.error('Ajax Error: ' + xhr.status + ' ' + thrownError); 
     } 
    }).then(componentLoaded()); 
} 

/** 
* Render the template onto the page 
* @param template, The mustache template to render the data with 
* @param data, {{object}} The data to render into the template 
* @param target, {{object}} The jQuery object for the element to append the rendered data to 
*/ 
function renderTemplate(template, data, target) { 
    var rendered = Mustache.render(template, data); 

    target.append(rendered); 
} 

/** 
* Render the component 
*/ 
$(document).ready(function() { 
    getTemplate(); 
}); 

請注意,componentLoaded()是在另一個文件中的函數。

回答

1

爲什麼不在成功函數中調用componentLoaded()?

function renderComponent() { 
    // Get Data 
    return $.ajax('JSON/testData.json',{ 
     dataType: 'json', 
     success: function(data) { 
      if(template != null) { 
       for(var i = 0; i < data.blocks.length; i++) { 

        renderTemplate(template, data.blocks[i], $('#container')); 
       } 
       componentLoaded(); 
      } 
      else { 
       console.error('Error: Template failed to load'); 
      } 
      // or here 
      // componentLoaded(); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      console.error('Ajax Error: ' + xhr.status + ' ' + thrownError); 
     } 
    }); 
} 
1

順便說一句,在回答你的問題,當你真的想用承諾將它寫這樣的:

... 
}).then(componentLoaded); 
... 

既然你執行功能componentLoaded(),同時將它傳遞給承諾,因此沒有什麼可以執行的承諾!

相關問題