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);
  }
}

** 风景 **

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

该模型

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

谢谢你们。

4

1 回答 1

0

在我看来,优点是对 View 的定义更清晰。在我看来,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);
});

我用两种方式都做过,即使使用合金,有时也有必要这样做,因为在 Titanium 中实现的 Backbone 的限制 - 但我认为如果你可以在标记中包含重复的 UI 组件,它会更容易阅读和维护。

于 2016-06-13T17:39:41.097 回答