I have a list of items I'm trying to display with Ember. For each of these items, I'd like to be able to dynamically select the view type to use to display it based on a "message_type" field in each model.
I currently have something like this, which totally sucks and is not scalable:
{{#each message in controller}}
{{#if message.isImage}}
{{view App.ImageMessageView}}
{{/if}}
....
{{#if message.isVideo}}
{{view App.VideoMessageView}}
{{/if}}
{{/each}}
How can you dynamically select a view based on a model's field in Ember?
Here is a similar question that showed 2 ways to do this: Collection of objects of multiple models as the iterable content in a template in Ember.js
rendering items based on a property or their type
I know of two ways to do this:
add a boolean property to each object and use a handlebars {{#if}} to check that property and render the correct view
extend Ember.View and use a computed property to switch which template is rendered based on which type of object is being rendered (based on Select view template by model type/object value using Ember.js)
Method 1
JS:
App.Post = Ember.Object.extend({
isPost: true
});
App.Bookmark = Ember.Object.extend({
isBookmark: true
});
App.Photo = Ember.Object.extend({
isPhoto: true
});
template:
<ul>
{{#each item in controller.stream}}
{{#if item.isPost}}
<li>post: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isBookmark}}
<li>bookmark: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isPhoto}}
<li>photo: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{/each}}
</ul>
Method 2
JS:
App.StreamItemView = Ember.View.extend({
tagName: "li",
templateName: function() {
var content = this.get('content');
if (content instanceof App.Post) {
return "StreamItemPost";
} else if (content instanceof App.Bookmark) {
return "StreamItemBookmark";
} else if (content instanceof App.Photo) {
return "StreamItemPhoto";
}
}.property(),
_templateChanged: function() {
this.rerender();
}.observes('templateName')
})
template:
<ul>
{{#each item in controller.streamSorted}}
{{view App.StreamItemView contentBinding=item}}
{{/each}}
</ul>
JSBin example - the unsorted list is rendered with method 1, and the sorted list is rendered with method 2
It would probably need some more thought, but here is what I have come up with quickly:
var get = Ember.get,
isGlobalPath = Ember.isGlobalPath,
normalizePath = Ember.Handlebars.normalizePath;
var getProp = function (context, property, options) {
if (isGlobalPath(property)) {
return get(property);
} else {
var path = normalizePath(context, property, options.data);
return get(path.root, path.path);
}
};
Ember.Handlebars.registerHelper('detect', function (definition, instance, options) {
Ember.assert("You must pass exactly two argument to the detect helper", arguments.length === 3);
Ember.assert("You must pass a block to the detect helper", options.fn && options.fn !== Handlebars.VM.noop);
var path = '_detect_' + definition.replace('.', '_').toLowerCase();
context = (options.contexts && options.contexts[0]) || this;
definition = getProp(context, definition, options);
instance = getProp(context, instance, options);
context.set(path, definition.detectInstance(instance));
return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], path, options);
});
Then you can use a helper like this:
{{#detect App.Definition instance}}
DETECTED
{{else}}
NOT DETECTED
{{/detect}}
Related
How to iterate over each model value and based on the value update the handlebar UI.
I am using ArrayController. Basically for a particular value in the model I want to change how I display it.
I am not sure what is wrong in the above code. But it does not function as required.
App.SomeStat = Ember.Object.extend({
target: null,
starts: null
}
{{#each stat in controller}}
{{#if isRestricted}} Do something..
{{/if}}
{{/each}}
App.SomestatController = Ember.ArrayController.extend({
isRestricted: function () {
this.forEach(function(target) {
var t= target.get('target');
return t >= MAGIC_NUMBER;
});
}.property('model.#each.target'),
});
You should setup the ArrayController itemController property to an ObjectController which extends the content for each array content.
App.ExtendIndexController = Ember.ObjectController.extend({
isRestricted: Em.computed(function () {
return this.get('name') === 'red';
}).property('name')
});
App.IndexController = Ember.ArrayController.extend({
itemController: 'extendIndex'
});
Then, you could access the added properties in your template when iterating the controller:
{{#each controller}}
<li>{{name}} ({{isRestricted}})</li>
{{/each}}
http://emberjs.jsbin.com/gexos/1/edit
This case is documented in the Ember guide but I think, this specific case should documented as well.
Try this:
App.CensusStat = Ember.Object.extend({
targetPc: null,
starts: null,
isRestricted: function () {
var offTarget = this.get('targetPc');
return (offTarget &&
(Math.abs(offTarget) >=
Ember.I18n.t('ps.label.census.offtarget.restricted.percentage')));
}.property('targetPc')
});
I would like to be able to define the model for a component template inside the Ember.Component js instead of inside the route where the component is sitting. I have not seen any examples which are doing this...
Here I have my component template:
<script type="text/x-handlebars" id="components/info-box">
<div class="infoBox box">
<p>
<label>
{{preUnits}}
</label>
<span>
{{value}}
</span>
</p>
</div>
</script>
And here is how I am placing it inside one route template:
{{info-box title='Total Area' dataDef='buddhaData:DataGet/site/areaNum'}}
What I would like to do is use my relevant Ember.Component to do some stuff with the parameters of the info-box and then return a model for it.
App.InfoBoxComponent = Ember.Component.extend({
buildIt: function(){
var container = $('#' + this.get('elementId') );
var title = this.get('title');
var preUnits = this.get('preUnits') || '';
var dataDef = this.get('dataDef');
// Do stuff with dataDef.
var model = {
preUnits: '$',
value: 5000
}
// Hopefully return model somehow.
},
didInsertElement: function(){
this.buildIt();
}
});
I want to be able to use this component inside a bunch of different routes, and I do not want to have to refer to the route that a particular info-box is inside of in order to give the info-box its model, is this possible, or should I use some other feature, like a regular template and the render helper?
Once you have the model object, just set properties on the component itself:
App.InfoBoxComponent = Ember.Component.extend({
buildIt: function(){
var container = $('#' + this.get('elementId') );
var title = this.get('title');
var preUnits = this.get('preUnits') || '';
var dataDef = this.get('dataDef');
// Do stuff with dataDef.
var model = {
preUnits: '$',
value: 5000
}
// Set component's preUnits and value properties directly
this.setProperty('preUnits', model.preUnits);
this.setProperty('value', model.value);
// or
this.setProperties(model);
// Hopefully return model somehow.
},
didInsertElement: function(){
this.buildIt();
}
});
You should use render if you'd like to define which model you want to use (if the model is different than the current context). If it's the same context, you should just use partials. You could also generate helper and pass in the model to that.
Ember.Handlebars.helper('autocomplete', Ember.View.extend({
templateName: 'controls/autocomplete',
filteredList: function() {
var list = this.get('list'),
filter = this.get('filter');
if (!filter) { return list; }
return list.filter(function(item) {
return item.name.indexOf(filter) !== -1;
});
}.property('list.[]', 'filter')
}));
Usage:
<script type="text/x-handlebars" data-template-name="application">
{{autocomplete list=list1}}
{{autocomplete list=list2}}
</script>
<script type="text/x-handlebars" data-template-name="controls/autocomplete">
<p>{{input type="text" value=view.filter}}</p>
<ul>
{{#each view.filteredList}}
<li >{{name}}</li>
{{/each}}
</ul>
</script>
Full example
I have a list of items I'm trying to display with Ember. For each of these items, I'd like to be able to dynamically select the view type to use to display it based on a "message_type" field in each model.
I currently have something like this, which totally sucks and is not scalable:
{{#each message in controller}}
{{#if message.isImage}}
{{view App.ImageMessageView}}
{{/if}}
....
{{#if message.isVideo}}
{{view App.VideoMessageView}}
{{/if}}
{{/each}}
How can you dynamically select a view based on a model's field in Ember?
Here is a similar question that showed 2 ways to do this: Collection of objects of multiple models as the iterable content in a template in Ember.js
rendering items based on a property or their type
I know of two ways to do this:
add a boolean property to each object and use a handlebars {{#if}} to check that property and render the correct view
extend Ember.View and use a computed property to switch which template is rendered based on which type of object is being rendered (based on Select view template by model type/object value using Ember.js)
Method 1
JS:
App.Post = Ember.Object.extend({
isPost: true
});
App.Bookmark = Ember.Object.extend({
isBookmark: true
});
App.Photo = Ember.Object.extend({
isPhoto: true
});
template:
<ul>
{{#each item in controller.stream}}
{{#if item.isPost}}
<li>post: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isBookmark}}
<li>bookmark: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isPhoto}}
<li>photo: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{/each}}
</ul>
Method 2
JS:
App.StreamItemView = Ember.View.extend({
tagName: "li",
templateName: function() {
var content = this.get('content');
if (content instanceof App.Post) {
return "StreamItemPost";
} else if (content instanceof App.Bookmark) {
return "StreamItemBookmark";
} else if (content instanceof App.Photo) {
return "StreamItemPhoto";
}
}.property(),
_templateChanged: function() {
this.rerender();
}.observes('templateName')
})
template:
<ul>
{{#each item in controller.streamSorted}}
{{view App.StreamItemView contentBinding=item}}
{{/each}}
</ul>
JSBin example - the unsorted list is rendered with method 1, and the sorted list is rendered with method 2
It would probably need some more thought, but here is what I have come up with quickly:
var get = Ember.get,
isGlobalPath = Ember.isGlobalPath,
normalizePath = Ember.Handlebars.normalizePath;
var getProp = function (context, property, options) {
if (isGlobalPath(property)) {
return get(property);
} else {
var path = normalizePath(context, property, options.data);
return get(path.root, path.path);
}
};
Ember.Handlebars.registerHelper('detect', function (definition, instance, options) {
Ember.assert("You must pass exactly two argument to the detect helper", arguments.length === 3);
Ember.assert("You must pass a block to the detect helper", options.fn && options.fn !== Handlebars.VM.noop);
var path = '_detect_' + definition.replace('.', '_').toLowerCase();
context = (options.contexts && options.contexts[0]) || this;
definition = getProp(context, definition, options);
instance = getProp(context, instance, options);
context.set(path, definition.detectInstance(instance));
return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], path, options);
});
Then you can use a helper like this:
{{#detect App.Definition instance}}
DETECTED
{{else}}
NOT DETECTED
{{/detect}}
I am trying to build a blog application with Ember. I have models for different types of post - article, bookmark, photo. I want to display a stream of the content created by the user for which I would need a collection of objects of all these models arranged in descending order of common attribute that they all have 'publishtime'. How to do this?
I tried something like
App.StreamRoute = Ember.Route.extend({
model: function() {
stream = App.Post.find();
stream.addObjects(App.Bookmark.find());
stream.addObjects(App.Photo.find());
return stream;
}
}
where the resource name is stream
But it doesn't work. I am using the latest released Ember 1.0.0 rc 2 and handlebars 1.0.0 rc 3 with jQuery 1.9.1 and ember-data.
Probably the way I am trying to achieve this whole thing is wrong. The problem is even if I am able to use the collection of objects of multiple models to iterate in the template, I would still need to distinguish between the type of each object to display its properties apart from the common property of 'publishtime'.
You can use a computed property to combine the various arrays and then use Javascript's built in sorting to sort the combined result.
Combining the arrays and sorting them
computed property to combine the multiple arrays:
stream: function() {
var post = this.get('post'),
bookmark = this.get('bookmark'),
photo = this.get('photo');
var stream = [];
stream.pushObjects(post);
stream.pushObjects(bookmark);
stream.pushObjects(photo);
return stream;
}.property('post.#each', 'bookmark.#each', 'photo.#each'),
example of sorting the resulting computed property containing all items:
//https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort
streamSorted: function() {
var streamCopy = this.get('stream').slice(); // copy so the original doesn't change when sorting
return streamCopy.sort(function(a,b){
return a.get('publishtime') - b.get('publishtime');
});
}.property('stream.#each.publishtime')
});
rendering items based on a property or their type
I know of two ways to do this:
add a boolean property to each object and use a handlebars {{#if}} to check that property and render the correct view
extend Ember.View and use a computed property to switch which template is rendered based on which type of object is being rendered (based on Select view template by model type/object value using Ember.js)
Method 1
JS:
App.Post = Ember.Object.extend({
isPost: true
});
App.Bookmark = Ember.Object.extend({
isBookmark: true
});
App.Photo = Ember.Object.extend({
isPhoto: true
});
template:
<ul>
{{#each item in controller.stream}}
{{#if item.isPost}}
<li>post: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isBookmark}}
<li>bookmark: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isPhoto}}
<li>photo: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{/each}}
</ul>
Method 2
JS:
App.StreamItemView = Ember.View.extend({
tagName: "li",
templateName: function() {
var content = this.get('content');
if (content instanceof App.Post) {
return "StreamItemPost";
} else if (content instanceof App.Bookmark) {
return "StreamItemBookmark";
} else if (content instanceof App.Photo) {
return "StreamItemPhoto";
}
}.property(),
_templateChanged: function() {
this.rerender();
}.observes('templateName')
})
template:
<ul>
{{#each item in controller.streamSorted}}
{{view App.StreamItemView contentBinding=item}}
{{/each}}
</ul>
JSBin example - the unsorted list is rendered with method 1, and the sorted list is rendered with method 2
It's a little complicated than that, but #twinturbo's example shows nicely how to aggregate separate models into a single array.
Code showing the aggregate array proxy:
App.AggregateArrayProxy = Ember.ArrayProxy.extend({
init: function() {
this.set('content', Ember.A());
this.set('map', Ember.Map.create());
},
destroy: function() {
this.get('map').forEach(function(array, proxy) {
proxy.destroy();
});
this.super.apply(this, arguments);
},
add: function(array) {
var aggregate = this;
var proxy = Ember.ArrayProxy.create({
content: array,
contentArrayDidChange: function(array, idx, removedCount, addedCount) {
var addedObjects = array.slice(idx, idx + addedCount);
addedObjects.forEach(function(item) {
aggregate.pushObject(item);
});
},
contentArrayWillChange: function(array, idx, removedCount, addedCount) {
var removedObjects = array.slice(idx, idx + removedCount);
removedObjects.forEach(function(item) {
aggregate.removeObject(item);
});
}
});
this.get('map').set(array, proxy);
},
remove: function(array) {
var aggregate = this;
array.forEach(function(item) {
aggregate.removeObject(item);
});
this.get('map').remove(array);
}
});
I have a controller object that's like:
MyApp.objController = Ember.ArrayController.create({
init: function(data) {
data.isValid = function() {
return (data.validity === "valid");
}
this.pushObject(MyApp.MyObj.create(data));
}
});
My view is like:
{{#each MyApp.objController}}
{{#if isValid}}
<some markup>
{{else}}
<some other markup>
{{/if}}
{{/each}}
I was assuming that the if conditional in Handlebars accepts both values and functions, but this doesn't seem to be the case. Is it actually possible, and I'm just doing it wrong?
Handlebars if statements only compares if a value exists, to if it is a falsy value (ie non-existant, 0, an empty string etc.). You have to write a custom helper function.
You could do it like this
Handlebars.registerHelper('isValid', function (value, options) {
if (value == "valid") {
return options.fn(this);
}
return options.inverse(this);
});
This registers a block helper. If the value you pass in evaluates to "valid" it returns the template following the the helper with the current data. If it does not evaluate to valid it returns the template following the else statement with the current data.
Then in your template you could use it like this
{{#each MyApp.objController}}
{{#isValid validity}}
<some markup>
{{else}}
<some other markup>
{{/isValid}}
{{/each}}
Otherwise, if you wanted to abide by the spirit of Handlebars and do a 'logic-less' template, set a flag before you render the template indicating whether or not that data is valid, then use the handlebars if helper with the flag.
You could also possible set up a generic function to handle this and other cases. See my answer in Logical operator in a handlebars.js {{#if}} conditional for an example for a generic if (similar to the above answer)
If you define your isValid as a property, you can use it in your if statement without creating a custom Handlebars helper, see http://jsfiddle.net/pangratz666/Dq6ZY/:
Handlebars:
<script type="text/x-handlebars" data-template-name="obj-template" >
{{view Ember.TextField valueBinding="age" }}
{{#if isValid}}
Si Si.
{{else}}
Nope!
{{/if}}
</script>
JavaScript:
App.MyObj = Ember.Object.extend({
isValid: function() {
return this.get('age') >= 18;
}.property('age')
});
Ember.View.create({
templateName: 'obj-template',
controller: App.MyObj.create({
age: 21
})
}).append();
You could create a custom Handlebars helper to do this.
Try this:
<ul>
{{#each subsites}}
{{#if this}}
<li>{{{WhatIsTheSiteFor this}}}</li>
{{else}}
<li>no found</li>
{{/if}}
{{/each}}
</ul>
The helper function WhatIsTheSiteFor:
Handlebars.registerHelper('WhatIsTheSiteFor', function(siteName) {
var subSiteName = '',
siteNameStr = '';
$.each(siteName, function(i, item) {
siteNameStr += item;
return siteNameStr;
});
if(siteNameStr === 's.gbin1.com') {
subSiteName = 'GB搜索引擎';
}
else if (siteNameStr === 'm.gbin1.com') {
subSiteName = 'GB手机阅读';
}
else if (siteNameStr === 'rss.gbin1.com') {
subSiteName = 'RSS消息订阅';
}
return subSiteName;
});
A demo can be found here: http://www.gbin1.com/gb/networks/uploads/71bb1c1e-0cd3-4990-a177-35ce2612ce81/demo6.html