Ember js: parentViewDidChange doesn't get triggered - view

If have a little game where images have to be dragged on the right hotspots of a larger image.
The little images are inside a containerView, the hotspots also are ContainerViews.
When i drop the images on a hotspot i use the following code in my drag-n-drop mixin to move the image in the dom:
Player.Droppable = Ember.Mixin.create({
drop: function(event) {
//get the view that was dragged
var viewId = event.originalEvent.dataTransfer.getData('Text');
var view = Ember.View.views[viewId];
//log the parent-view: App.AnswerListView
console.log(view.get('parentView').constructor);
//detach the view from the original containerView
var parentView = view.get('parentView');
parentView.removeObject(view);
//attach it to the hot-spot-containerview
this.addObject(view);
//logging this gives a different result: App.HotspotView
console.log(view.get('parentView').constructor);
event.preventDefault();
return false;
}
});
The view i'm dragging is an App.AnswerView. What i'm expecting from the docs is that the function parentViewDidChange on the AnswerView is triggered, but that doesn't happen:
App.AnswerView = Ember.View.extend(App.Draggable, {
templateName: "answer",
classNameBindings: [':answer', 'this.content.isSelected:selected'],
click: function(evt){
this.get('controller').send('answerClicked', this.content);
},
parentViewDidChange: function(){
this.get('controller').send('answerMoved', this.content);
},
});
The docs say: Called when the parentView property has changed. In my case, it is changed. Is this a bug, or am I missing something here?
TIA

This issue was a bug and got resolved in the 1.0.0 final
https://github.com/emberjs/ember.js/issues/2423

pushObject and removeObject are methods, inherited from the Ember.MutableArray Mixin, that the Ember.ContainerView extends. If you look at Ember's source code for ContainerView (https://github.com/emberjs/ember.js/blob/v1.0.0-rc.2/packages/ember-views/lib/views/container_view.js#L15), you will see that ContainerView does not override those methods, thus they only manipulate its childViews array, not the view's parent view.
You should find methods that manipulate the '_parentView' property here instead: (https://github.com/emberjs/ember.js/blob/v1.0.0-rc.2/packages/ember-views/lib/views/view.js#L2018) - in the Ember.View's implementation.
So in short, use:
removeChild instead of removeObject, to delete a child view from your ContainerView
createChildView + pushObject instead of 'addObject', if you want to add a new child view to a ContainerView.
Example Code:
Player.Droppable = Ember.Mixin.create({
drop: function(event) {
//get the view that was dragged
var viewId = event.originalEvent.dataTransfer.getData('Text');
var view = Ember.View.views[viewId];
//log the parent-view: App.AnswerListView
console.log(view.get('parentView').constructor);
//detach the view from the original containerView
var parentView = view.get('parentView');
parentView.removeChild(view);
//attach it to the hot-spot-containerview
this.createChildView(view);
this.pushObject(view);
//logging this gives a different result: App.HotspotView
console.log(view.get('parentView').constructor);
event.preventDefault();
return false;
}
});

Related

How to change the label of widget(Firefox Add-on SDK)

I want to change the label of a widget when user click it, then I write the code looks like this:
var widgets = require("sdk/widget");
var statusBar = widgets.Widget({
id: "patchouliStatus",
label: "Wait Page Loading...",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(){
this.contentURL = "http://www.google.com/favicon.ico";
this.label = "Clicked";
}
});
When I click the widget, the icon has changed, but nothing happen to the label.I move the mouse to the widget and it still show "Wait Page Loading...".Is there a way to dynamically change the label?
Firefox: v27.0.1
Add-on SDK: v1.15
Widget's label is read-only. You must use tooltip attribute to show the user a text on mouse hover, this way:
var widgets = require("sdk/widget");
var statusBar = widgets.Widget({
id: "patchouliStatus",
label: "Wait Page Loading...",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(){
this.contentURL = "http://www.google.com/favicon.ico";
this.tooltip = "Clicked";
}
});
As docs says somewhere in this section -I think it could be more clearly documented-, tooltip value is an "optional text to show when the user's mouse hovers over the widget. If not given, the label is used". Also, examples in that section don't make it clear enough as I think they should.
Ok man thanks for the XPI, change changeLabel function to this, my above was really bugged.
function changeLabel(str){
var DOMWindows = Services.wm.getEnumerator('navigator:browser');
while (DOMWindows.hasMoreElements()) {
var aDOMWindow = DOMWindows.getNext();
var myWidget = aDOMWindow.document.getElementById('widget:jid1-njALX8gXKY872g#jetpack-patchouliStatus');
if (myWidget) {
Services.appShell.hiddenDOMWindow.console.info('myWidget:', myWidget);
myWidget.setAttribute('label', str);
myWidget.setAttribute('tooltiptext', 'tooltip changed');
} else {
Services.appShell.hiddenDOMWindow.console.info('myWidget null:', myWidget);
}
}
}
It also seems that the id of your widget starts with tyour addon id name.
Now I gave you the enumerator function because that goes over all windows and you can add event listener. But really if you just want to target the one that was clicked just get the most recent window, as that will obviously hold the correct window with your widget as we just clicked there and the event listener fires on click.
Change changeLabel to this:
function changeLabel(str){
var aDOMWindow = Services.wm.getMostRecentWindow('navigator:browser');
var myWidget = aDOMWindow.document.getElementById('widget:jid1-njALX8gXKY872g#jetpack-patchouliStatus');
if (myWidget) {
Services.appShell.hiddenDOMWindow.console.info('myWidget:', myWidget);
myWidget.setAttribute('label', str);
myWidget.setAttribute('tooltiptext', 'tooltip changed');
} else {
Services.appShell.hiddenDOMWindow.console.info('myWidget null:', myWidget);
}
}
Also that Services.appShell.hiddenDOMWindow.console.info is just something nice to debug, I left it in there so you can see how it works. It logs to "Browser Console" (Ctrl+Shift+J).
As a final note I used a non-sdk solution by requiring chrome. they advise you not to do that because they want you to use the SDK functions I don't know about SDK but you can use the getEnumerator and recentWindow function by requiring window/utils it looks like:
Read window/utils article here
I'll give you non-sdk solution here but someone will have to help convert it to sdk solution. You can paste this in your code it will work though.
Im not sure how the element is inserted into the dom but I guessed.
var {Cu, Ci} = require('chrome'); //if you want to paste this into scratchpad with with Environemnt set to Browser than dont need this line, this line is for sdk
var DOMWindows = Services.wm.getWindowEnumerator(null);
while (DOMWindows.hasMoreElements()) {
var aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
var myWidget = aDOMWindow.querySelector('#patchouliStatus'); //im not exactly sure how the element is inserted in the dom but im guessing here
if (myWidget) {
myWidget.label = 'rawr';
}
}

How to use SuperScrolloRama with Backbone.js Views

I am trying to understand how to use a plugin like http://johnpolacek.github.io/superscrollorama/, with Backbone.js by integrating it into my Views. I know that I need to hook into the backbone View-Events, but I want to do a horizontal scroll with the plugin, and I don't know of a horizontal scroll-event. How can I still utilize the plugin? Thanks in advance for any ideas.
Views:
var ArtistsView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.cleanUp();
$("body").attr('id','artists');
this.render();
},
events: {
"click div.open" : "largeArtViewOpen",
"click div.close" : "largeArtViewClose",
},
render: function () {
this.collection.each(function(model) {
var artistView = new ArtistView({ model: model });
this.$el.append(artistView.render().el);
}, this);
console.log('and a new view was rendered!')
return this;
},
cleanUp: function(){
if (this != null) {
this.remove();
this.unbind();
console.log('View was removed!');
}
},
largeArtViewOpen: function(e){
var thisArt = $(e.currentTarget).parent().attr("class");
console.log(thisArt);
$("#open-view, li."+thisArt).show();
},
largeArtViewClose: function(e){
//var thisArt = $(e.currentTarget).parent().attr("class");
console.log('clicked!');
$("#open-view, ul#large li").hide();
},
scrollFx: function(){
var controller = $.superscrollorama({
isVertical:false
});
controller.addTween('h2#fade-it', TweenMax.from( $('h2#fade-it'), .5, {css:{opacity: 0}}), 800);
//$('h2#fade-it').css({'color':'#dbdbdb'});
console.log('scroll message!');
},
});
var ArtistView = Backbone.View.extend({
tagName:'li',
className:'artistLink not-active',
render: function(){
this.id = this.model.get('idWord')+"-menu-item";
this.$el.attr('id', this.id).html(this.template(this.model.toJSON()));
return this;
},
});
So, in the past 3 days since I've asked this question, I've spent some time trying different scrollable 'targets' for Superscrollorama...Document vs. Window vs. Body vs. other DOM elements within the HTML, and the questions that I've had to consider are, should the scroll event be bound to the View's top element? Should it be bound to the body, but initialized in the view? In both cases I tried, I couldn't get the scroll events to continuously fire...this may just be due to bad code, but I couldn't make it happen.
So, what I arrived at, was, avoiding the view entirely: I instantiating and called Superscrollorama in a function called scrollFx() within a separate 'helper.js' document, and then called scrollFx() from my view's router.
I'm thinking I will just empty the target's styles and unbind any existing scroll events in the beginning of scrollFx(), before I call the Superscrollorama function so that the resulting scroll styles/animations are cleaned up, and events aren't exponentially bound.
I'm still very much working through these issues, though now the scroll events are working, so if anyone happens to read through this train of thought, please feel free to add your two sense, especially, if you have better ideas about re-implementing the Superscrollorama function within the View itself.
Thanks.

Edit button with comments using MooTools/AJAX

So I'm using a PHP API to interact with, to build a forum using MooTools. I can get comments from my database and add comments, but I want to inject an edit button to coincide with each comment.
I inject the comments using:
function domReady() {
$('newComment').addEvent('submit', addComment);
}
function addComment(e){
e.stop();
var req = new Request({
url:'control.php?action=insertPost',
onSuccess:addajaxSuccess
}).post(this);
}
function addajaxSuccess(idNo) {
new Element('span',{
'text':'Post successful.'
}).inject($(newComment));
$('commentList').empty();
domReady();
}
I want to attach an edit button to each comment injected, and add an event listener on the button to change the comment into a textarea for editting, with an update button.
Any ideas?
If you want to bind a global events to a dynamic content you have better look into Element Delegation In mootools.
Basically it's give you the ability to bind event to some container and "listen" to events of that children container base on selectors. I made you a little example here:
http://jsfiddle.net/xwpmv/
mainContainer.addEvents({
'click:relay(.mt-btn)': function (event, target) {
var btn = target;
if(btn.get('value') == 'Edit'){
btn.set('value','Done Editing');
var content = btn.getPrevious();
content.setStyle('display','none');
var textarea = new Element('textarea').set('text',content.get('text'));
textarea.inject(btn,'before');
}
else{
btn.set('value','Edit');
var textarea = btn.getPrevious();
var new_value = textarea.get('value');
textarea.destroy();
var content = btn.getPrevious();
content.set('text',new_value);
content.setStyle('display','block');
}
}
});
Here you can see the mainContainer listen to the click event of every element who has mt-btn class (the buttons)
You have several errors in your code but maybe it is just an example so I didn't relate to it.

Backbone click event fires events for all collection rather than model

Can't figure out what's wrong. When I click on a model title, it fetches all models in collection at once rather than fetch one model. If I move this event from logView to logsView it works properly but doesn't have access to model, well I can find this model using index or ant other model's ID but don't think this is a nice way.
var Log = Backbone.Model.extend({});
window.LogsList = Backbone.Collection.extend({
model:Log,
url:function (tag) {
this.url = '/logs/' + tag;
return this;
}
});
window.colList = new LogsList();
window.logView = Backbone.View.extend({
el:$('.accordion'),
template:_.template($('#log').html()),
initialize:function () {
this.model.bind('add', this.render, this);
},
events:{
"click .accordion-toggle" :"getLogBody"
},
render:function () {
return this.template(this.model.toJSON());
},
getLogBody:function () {
this.model.fetch();
}
});
window.LogsView = Backbone.View.extend({
el:$("#content"),
initialize:function (options) {
colList.bind('reset', this.addAll, this);
colList.url(options.data).fetch();
},
addOne:function (model) {
var view = new logView({model:model});
$("#accordion").append(view.render());
},
addAll:function () {
colList.each(this.addOne);
}
});
window.listView = new LogsView({data:"Visa_Cl"});
The problem is caused by your el in the LogView: el:$('.accordion')
Backbone's view events are scope to the view's el. In this case, you've specified the view's el as ALL HTML elements with a class of "accordion". Therefore, when you click on any of your HTML elements with this class, the code runs for all of them, which is why you are seeing this behavior.
This article will show you a few options for doing what you want, correctly:
Backbone.js: Getting The Model For A Clicked Element
I would also recommend reading this one, to better understand the use of el in Backbone, and a few of the tricks and traps of it:
Backbone.js: Object Literals, Views Events, jQuery, and el

Backbone.js views & parent elements

Does it make sense to let a backbone.js-view know about it's parent element, when you have a simple view containing very little logic, or is it bad practice?
Like this:
var BooklistRow = Backbone.View.extend({
tagName: "li",
parent: "#booklist",
render: function() {
$(this.el).html("<b>" + this.model.get("title") + "</b>");
$(this.parent).append(this.el);
return this;
}
});
It is better if a view knows nothing outside of itself. This will make it more reusable.
Also in your example, you are adding to the parent on render. At some point, you may want to re-render the BooklistRow after it is already appended to the parent.
I think it is better for the parent to render and add the children:
var Booklist = Backbone.View.extend({
tagName: "ul",
render: function() {
// maybe should remove existing books here first
this.model.each(this.addOneBook);
return this;
},
addOneBook: function(book) {
var view = new BooklistRow({
model: book
});
$(this.el).append(view.render().el);}});
Now, if a single book changes, it can re-render itself without the list even knowing.

Resources