1

我即将从远程检索数据并创建模型和集合,这里是应用程序(控制器,视图和模型)的每个部分。 如果我真的明白在钛中使用模型就像存储到数据库中一样,即使在获取所有数据后没有互联网连接,数据仍然存在。 下面的代码运行良好,连接丢失后没有显示任何数据,所以我问自己,在钛中使用模型而不是使用经典方式有什么优势:从xhr中检索并显示数据? 2-我的第二个问题(如果我错了)检索数据并存储到模型后,我可以检索它没有xhr再次在另一个页面内? 3-最后一个:从alloy.js中检索数据并保存到模型是一种很好的做法,因为我需要在所有应用程序页面中使用数据?钛加速器模型和集合持久性

控制器

// This is an istance of my xhr library 
 
var XHR = require('xhr'); 
 
var xhr = new XHR(); 
 

 
$.win.addEventListener('open', function(){ 
 
    
 
    url = 'mydomain.com/api/get_posts'; 
 
    xhr.get(url, onSuccess, onError); 
 

 
}); 
 

 
function onSuccess(response){ 
 
    
 
    if(typeof response !== null){ 
 
    datas = JSON.stringify(response.data); 
 
    postsModel = []; 
 
    _.each(datas, function(data){ 
 
     
 
    /* Create model */ 
 
    postsModel.push(Alloy.createModel('mypostsmodel',{ 
 
     title : data.title, 
 
     id : data.id 
 
    })); 
 
     
 
    }); 
 
    
 
    $.posts.reset(postsModel); 
 
    } 
 
}

** THE VIEW **

<Alloy> 
 
\t <Collection src="myposts" instance="true" id="myposts" /> 
 
\t <Window id="win" title="Inscription" class="container" > 
 
\t \t <View id="posts_view" class="myposts" dataCollection="$.myposts"> 
 
\t \t \t \t <View postId="{id}" class="post_item"> 
 
\t \t \t \t \t <Label class="post_label" text="{title}" /> 
 
\t \t \t \t \t <Label class="exp" id="exp_{id}" text="" /> 
 
\t \t \t \t </View> 
 
\t \t \t </View> 
 
\t \t </View> 
 
</Alloy>

THE MODEL

exports.definition = { 
 
\t config: { 
 
\t \t "columns": { 
 
      "title": "Text", 
 
      "id": "Integer" 
 
     }, 
 
     "defaults": { 
 
      "title": "-", 
 
      "id": "-" 
 
     }, 
 
\t \t adapter: { 
 
\t \t \t type: "sql", 
 
\t \t \t collection_name: "myposts" 
 
\t \t } 
 
\t }, 
 
\t extendModel: function(Model) {}, 
 
    ...

谢谢大家。

回答

0

我认为在视图中有更清晰的定义。在我看来,Alloy最大的贡献就是能够更清楚地将您的视图与驱动应用程序的逻辑分开。你的逻辑也被简化了(在大多数情况下!),因为你需要做的只是将数据添加到集合中,并且Alloy处理显示。

的替代品,你是如何做的:

_.each(datas, function(data){ 
var container = Ti.UI.createView({class: "post_item"}), 
    title = Ti.UI.createLabel({ 
    text: data.title, 
    class: "post_label" 
    }), 
    exp = Ti.UI.createLabel({class: "exp"}); 

    container.add(title); 
    container.add(exp); 
    $.posts_view.add(container); 
}); 

我已经做到了两者兼得,甚至与合金,有时必须要做到这一点,因为骨干的局限性,如实施钛 - 但我想清楚如果你可以在标记中包含你的重复UI组件,它更容易阅读和维护。

+0

嗨,感谢您的回复,我真的很感谢,我只是想知道如何从我的代码中坚持这些数据?谢谢。 – user44321