I have a view in Titanium Alloy which loops through a list of videos in a collection, like so:

<View dataCollection="videos" dataFilter="recentlyAddedFilter">
    <ImageView image="{img}" width="200">
          <Label text="{title}"></Label>  
    </ImageView>
</View>

And I have a filter function called recentlyAddedFilter, defined in my controller like so:

function recentlyAddedFilter(collection) {
    return collection.where({title:'A title'});
}

I'm going to create multiple versions of this view component, so I would like the filter function to be able to access each individual component that it is applied to, just like I can use the collection inside the filter function. So it would be great if I could do something like this:

function recentlyAddedFilter(collection) {
    theComponent.width = "200dp"; // change property on component that calls this function
    return collection.where({title:'A title'});
}

Is there a way that I can do this?

有帮助吗?

解决方案

Instead use the dataTransform function to add an attribute to the JSON used to construct the view, and then with the added custom attribute, call it much like any other attribute. For example:

<View dataCollection="videos" dataFilter="recentlyAddedFilter" 
                              dataTransform="recentlyAddedTransform">
    <!-- Pass the customWidth attribute that was added in the transform function -->
    <ImageView image="{img}" width="{customWidth}">
          <Label text="{title}"></Label>  
    </ImageView>
</View>

So your controller would look like this:

// Takes a collection
function recentlyAddedFilter(collection) {
    return collection.where({title:'A title'});
}

// Takes a model
function recentlyAddedTransform(model) {
    // Make sure to convert the model to JSON
    var transform = model.toJSON();
    // Add a custom width attribute to the model
    transform.customWidth = "200dp"; 
    return transform;
}

Remember that in the dataTransform function you are working with an individual model, but you are returning JSON.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top