I have a answers list like below:
each list item is a backbone model.
{
title: 'answer title...',
content: 'answer content...',
voteStatus: 'up'
}
When I click up-vote or down-vote, The model's voteStatus will be change, and this answer item be re-render.
If there have a picture in answer's content, the picture will be re-render too, But this is not what I want.
How could I just re-render the vote button when I just change voteStatus?
Have a subview inside your AnswerView that is only responsible for rendering the voting arrows, VotingArrowsView. You would initialize this subview inside the initialize function of AnswerView and then prepend the subview's el to the parent view's el when rendering the parent view:
var AnswerView = Backbone.View.extend({
initialize: function(options){
this.template = _.template($('#answerTmpl').html());
this.votingArrowsView = new VotingArrowsView({ model: this.model });
...
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
this.$el.prepend(this.votingArrowsView.render().el);
return this;
},
...
});
var VotingArrowsView = Backbone.View.extend({
initialize: function(options){
this.template = _.template($('#votingArrowsTmpl').html());
this.listenTo(this.model, 'change:voteStatus', this.render);
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
Related
I'm trying add a delete button with an ember action from a controller. For some reason Ember.Handlebars.compile('<button {{action "deletePerson"}}>Delete</button> returns a function and not the compiled string.
Here's a jsbin
Here's the relevant portion of code:
App.ApplicationController = Ember.Controller.extend({
columns: function() {
...
buttonColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: 'Action',
getCellContent: function(row) {
var button = Ember.Handlebars.compile('<button {{action "deletePerson" this}}>Delete</button>');
return button; // returns 'function (context, options) { ...'
}
});
...
}.property()
...
After looking through the link from #fanta (http://addepar.github.io/#/ember-table/editable) and a lot of trial and error, I got it working.
Here's the working jsbin.
Here are some key points:
Instead of using getCellContent or contentPath in the ColumnDefinition, you need to use tableCellViewClass and to create a view that will handle your cell
Pass in this to the action on your button — and modify content off that. One gotcha is to edit content, you need to copy it using Ember.copy
Here's the relevant code:
App.ApplicationController = Ember.Controller.extend({
columns: function() {
...
buttonColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: 'Action',
tableCellViewClass: 'App.PersonActionCell'
});
...
}.property(),
onContentDidChange: function(){
alert('content changed!');
}.observes('content.#each'),
...
});
App.PersonActionCell = Ember.Table.TableCell.extend({
template: Ember.Handlebars.compile('<button {{action "deletePerson" this target="view"}}>Delete</button>'),
actions: {
deletePerson: function(controller){
// Will NOT work without Ember.copy
var people = Ember.copy(controller.get('content'));
var row = this.get('row');
// For some reason people.indexOf(row) always returned -1
var idx = row.get('target').indexOf(row);
people.splice(idx, 1);
controller.set('content', people);
}
}
});
I'm learning backbone.js and I'm building my first multimodule app. I'm getting an error that I've never seen before and I think I know the reason, but I can't see how to fix it. I believe it's because the model isn't actually available to the view yet, but I can't see why.
The error is:
Uncaught TypeError: Object function (){ return parent.apply(this, arguments); } has no method 'toJSON'
This is for line 11 in my view, msg.App.MessageListItemView.
Here's my model:
var msgApp = msgApp || {};
msgApp.Message = Backbone.Model.extend();
Here's my collection:
var msgApp = msgApp || {};
msgApp.MessageCollection = Backbone.Collection.extend({
model: msgApp.Message,
url: MESSAGES_API // Call to REST API with Tastypie
});
Here's my list view:
var msgApp = msgApp || {};
msgApp.MessageListView = Backbone.View.extend({
el: '#gps-app',
initialize: function() {
this.collection = new msgApp.MessageCollection();
this.collection.fetch({reset: true});
this.render();
this.listenTo( this.collection, 'reset', this.render );
},
// render messages by rendering each message in it's collection
render: function() {
this.collection.each(function(item){
this.renderMessage(item);
}, this);
},
// render a message by creating a MessageView and appending the the element it renders to the messages element
renderMessage: function(item) {
var messageView = new msgApp.MessageListItemlView({
model: msgApp.Message
});
this.$el.append(messageView.render().el);
}
});
Here's my item view:
var msgApp = msgApp || {};
msgApp.MessageListItemlView = Backbone.View.extend({
tagName: 'li',
className: 'message-list-item',
template: _.template($('#messageListItem').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
And here is my router:
var AppRouter = Backbone.Router.extend({
routes: {
'messages/': 'allMessages',
},
allMessages:function() {
this.messageList = new msgApp.MessageCollection();
this.messageListView = new msgApp.MessageListView({model:this.messageList});
console.log('I got to messages!');
},
});
var app_router = new AppRouter;
I'm looking for any and all suggestions. I'm a noob to begin with, and this is my first multimodule app so I'm having a little trouble managing scope I think.
Thanks for you time!
try to change model: msgApp.Message in msgApp.MessageListView like this:
// render a message by creating a MessageView and appending the the element it renders to the messages element
renderMessage: function(item) {
var messageView = new msgApp.MessageListItemlView({
model: item
});
this.$el.append(messageView.render().el);
}
model parameter in views don't expect type of model, but instance of some model. Hope this helps.
How do i change an elements class on click via ember.js, AKA:
<div class="row" {{bindAttr class="isEnabled:enabled:disabled"}}>
View:
SearchDropdown.SearchResultV = Ember.View.extend(Ember.Metamorph, {
isEnabled: false,
click: function(){
window.alert(true);
this.isEnabled = true;
}
});
The click event works as window alert happens, I just cant get the binding to.
The class is bound correctly, but the isEnabled property should be modified only with a .set call such as this.set('isEnabled', true) and accessed only with this.get('isEnabled'). This is an Ember convention in support of first-class bindings and computed properties.
In your view you will bind to a className. I have the following view in my app:
EurekaJ.TabItemView = Ember.View.extend(Ember.TargetActionSupport, {
content: null,
tagName: 'li',
classNameBindings: "isSelected",
isSelected: function() {
return this.get('controller').get('selectedTab').get('tabId') == this.get('tab').get('tabId');
}.property('controller.selectedTab'),
click: function() {
this.get('controller').set('selectedTab', this.get('tab'));
if (this.get('tab').get('tabState')) {
EurekaJ.router.transitionTo(this.get('tab').get('tabState'));
}
},
template: Ember.Handlebars.compile('<div class="featureTabTop"></div>{{tab.tabName}}')
});
Here, you have bound your className to whatever the "isSelected" property returns. This is only true if the views' controller's selected tab ID is the same as this views' tab ID.
The code will append a CSS class name of "is-selected" when the view is selected.
If you want to see the code in context, the code is on GitHub: https://github.com/joachimhs/EurekaJ/blob/netty-ember/EurekaJ.View/src/main/webapp/js/app/views.js#L100
Good answers, however I went down a different route:
SearchDropdown.SearchResultV = Ember.View.extend(Ember.Metamorph, {
classNameBindings: ['isSelected'],
click: function(){
var content = this.get('content');
SearchDropdown.SelectedSearchController.set('content', content);
var loadcontent = this.get('content');
loadcontent.set("searchRadius", $("select[name=radius]").val());
SearchDropdown.LoadMap.load(content);
},
isSelected: function () {
var selectedItem = SearchDropdown.SelectedSearchController.get('content'),
content = this.get('content');
if (content === selectedItem) {
return true;
}
}.property('SearchDropdown.SelectedSearchController.content')
});
Controller:
SearchDropdown.SelectedSearchController = Ember.Object.create({
content: null,
});
Basically stores the data of the selected view in a controller,
Fiddle:
http://jsfiddle.net/lifeinafolder/mpcRr/
Essentially, I want to hide the current 'visible' item and make the next one 'visible' but toggleProperty doesn't seem to be working on the childView object. It just silently fails and throws no errors as well.
A CollectionView will show all items in the collection, which is not what you want. I would implement a standard view that houses the collection and displays the next button and a slide view within it that displays the selected slide when the container view sets the selected slide as content on the slide view.
A quite ugly solution, almost working. I kept the way of switching views.
The template is the same, the js looks like this:
App = Ember.Application.create();
App.slides = Ember.ArrayProxy.create({
content:[]
});
App.slidesCollectionView = Ember.CollectionView.extend({
contentBinding:"App.slides",
tagName:'div',
emptyView: Ember.View.extend({
template: Ember.Handlebars.compile("<div class=\"placeholder\">placeholder</div>")
}),
itemViewClass:"App.slideView",
classNames:["slideshow"],
click:function(){
var t = Ember.ArrayProxy.create({ content: this.get('childViews') });
var selected = t.findProperty('isVisible', true);
if(selected){
var nextSlide = t.objectAt(selected.get('contentIndex') + 1);
selected.set('isVisible', false);
if(nextSlide){
nextSlide.set('isVisible', true);
}else{
t.get('firstObject').set('isVisible', true);
}
}else{
t.get('firstObject').set('isVisible', true);
}
}
});
App.slideView = Ember.View.extend({
templateName: 'slide-item',
tagName:'div',
isVisible: false,
classNames:['slide'],
classNameBindings:['isVisible:selected']
});
setTimeout(function(){
App.slides.pushObjects([
Ember.Object.create({val:'a',index:0}),
Ember.Object.create({val:'b',index:1}),
Ember.Object.create({val:'c',index:2}),
Ember.Object.create({val:'d',index:3}),
Ember.Object.create({val:'e',index:4}),
Ember.Object.create({val:'f',index:5})
])},2000);
the fiddle:
http://jsfiddle.net/Sly7/dd6at/
I have an app which lists albums. When album is clicked on both AlbumView and App.overlay (also a view) are displayed.
App.overlay = Ember.View.create({...}) (Lightbox-like overlay).
and:
App.AlbumView = Ember.View.extend({
// close the selected album view by closing the overlay
close: function() {
App.overlay.close();
}
});
And here's the problem: I want to be able to close those both views by clicking on the overlay, but I want overlay to remain independent of AlbumView, so that I can use the overlay in other places (i.e. without introducing a coupling between the two). How can I do it?
Here is my current implementation, with tight coupling, which I really don't like:
App.overlay = Ember.View.create({
// handle clicking anywhere on the overlay
click: function() {
this.close();
},
// close the overlay (setting selectedAlbum's controller content to null hides the AlbumView)
close: function() {
App.selectedAlbumController.set('content', null); // this should not be here
this.remove();
}
});
I'm only just learning ember, so take this with a grain of salt...
You could add a 'visible' property to the overlay, and then observe it from the other AlbumView. Like this:
var overlay = Ember.View.create({
visible: true,
click: function() {
this.close();
},
close: function() {
this.set('visible', false);
this.remove();
}
});
App.AlbumView = Ember.View.extend({
overlayClosed: function() {
App.selectedAlbumController.set('content', null);
this.remove();
}.observes('overlay.visible')
});
What about extracting your close method in a mixin?
App.AlbumClosing = Ember.Mixin.create({
close: function() {
App.selectedAlbumController.set('content', null);
this.remove();
}
});
var overlay = Ember.View.create(App.AlbumClosing, {
click: function() {
this.close();
}
});