Computed Property not firing - ember.js

I have a computed property cookieToggle that I'm using in a LoginController. The basic idea is that it would observe the username and rememberMe fields and set or clear the username cookie as appropriate. Unfortunately when I update either of the dependant fields it never calls the cookieToggle function (as observed by the lack of the console message that every call should produce). My main question is: why not? My secondary question is: is this a reasonable use of Ember's computed property?
App.LoginController = Ember.ObjectController.extend({
CLIENT_ID: 1,
username: null,
password: null,
rememberMe: false,
cookieToggle: function() {
var rememberMe = this.get('rememberMe');
var username = this.get('username');
console.log("cookie toggle");
if (rememberMe) {
$.cookie('auth_username', username);
} else {
$.removeCookie('auth_username');
}
return rememberMe;
}.property('rememberMe','username'),
init: function() {
this._super();
if ($.cookie('auth_username')) {
this.set('username', $.cookie('auth_username'));
this.set('rememberMe', true);
}
},
loginUser: function() {
var router = this.get('target');
var data = this.getProperties('username', 'password', 'rememberMe');
var user = this.get('model');
$.post('/api/oauth/user_credentials', { username: data.username, password: data.password, client_id: this.get('CLIENT_ID') }, function(results) {
// App.AuthManager.authenticate(results.api_key.access_token, results.api_key.user_id);
console.log(results);
$.cookie('auth_user', results.user.id);
router.transitionTo('users/login');
});
}
});

A computed property is not the right decision in this case. You want to use an Observer. You even use this verb yourself, right? :-) Just change your declaration from property to observes :
cookieToggle: function() {
var rememberMe = this.get('rememberMe');
var username = this.get('username');
console.log("cookie toggle");
if (rememberMe) {
$.cookie('auth_username', username);
} else {
$.removeCookie('auth_username');
}
}.observes('rememberMe','username') // will fire every time when one of those properties change

Related

Emberjs - how to reset a field on a component after saving?

I have an embedded object called Comment, inside a Game. Each game can have many Comments.
When a user (called a Parent) views the game page, they can leave a comment.
The problem I have is that I cannot seem to reset the body of the comment field back to empty after the comment is saved.
This is the component:
MyApp.AddCommentComponent = Ember.Component.extend({
body: '',
actions: {
addComment: function() {
var comment, failure, success;
if (!!this.get('body').trim()) {
comment = this.store.createRecord('comment', {
body: this.get('body'),
game: this.get('game'),
parent_id: this.get('parent_id'),
parent_name: this.get('parent_name')
});
success = (function() {
this.set('body', '');
});
failure = (function() {
return console.log("Failed to save comment");
});
return comment.save().then(success, failure);
}
}
}
});
The error is on the 'this.set' line - this.set is not a function
All the examples I find are about doing this in a controller or by creating a new record upon route change (but the route is not changing in my example, since it is just adding another embedded object to the existing page).
You are using
this.set('body', '');
in success, but the scope of this here is changed, you need to keep the controller scope and set the body to empty string like
MyApp.AddCommentComponent = Ember.Component.extend({
body: '',
actions: {
addComment: function() {
var that = this;
var comment, failure, success;
if (!!this.get('body').trim()) {
comment = this.store.createRecord('comment', {
body: this.get('body'),
game: this.get('game'),
parent_id: this.get('parent_id'),
parent_name: this.get('parent_name')
});
success = (function() {
that.set('body', '');
});
failure = (function() {
return console.log("Failed to save comment");
});
return comment.save().then(success, failure);
}
}
}
});
When you introduce a function, you must remember that the value for this is not (necessarily) the same as the enclosing scope's value for this. Save the reference to the Component to use in a closure, like this:
MyApp.AddCommentComponent = Ember.Component.extend({
body: '',
actions: {
addComment: function() {
var comment, failure, success;
var self= this;
if (!!this.get('body').trim()) {
comment = this.store.createRecord('comment', {
body: this.get('body'),
game: this.get('game'),
parent_id: this.get('parent_id'),
parent_name: this.get('parent_name')
});
success = (function() {
self.set('body', '');
});
failure = (function() {
return console.log("Failed to save comment");
});
return comment.save().then(success, failure);
}
}
}
});

How to bind a model property (from controller) without it firing validation right away?

I have a simple model backed controller with a simple validation on fullname. I added the validation to the models error computed property as shown below. It' works great except that this computed property is "fired" right away showing the "please enter a username" error right when the form is rendered.
Question is -how should I so this to get the nice computed property/2 way data bound property and error message but ... something that won't fire right away (instead waiting for the user to type something first).
var UserController = Ember.Controller.extend({
actions: {
submit: function() {
//verify model is legit ... transitionToRoute if so
}
}
});
var User = Ember.Object.extend({
enteredUsername: "",
username: function() {
var enteredUsername = this.get("enteredUsername");
return enteredUsername.trim();
}.property("enteredUsername"),
usernameError: function() {
var username = this.get("username");
if (!username) {
return "please enter a username";
}
}.property("username")
});
{{input type="text" value=model.enteredUsername}}
<span class="input-error">{{model.usernameError}}</span>
Like #Sisir said, you may need to have some sort of variable to check if the model value is dirty. Here is a way to get that implemented. Basically a model property will comprise of a value and isDirty property. So enteredUsername will be
enteredUsername: {
value: '',
isDirty: false
}
Your modified code will look like
var User = Ember.Object.extend({
enteredUsername: {
value: '',
isDirty: false
},
username: function() {
var value = this.get("enteredUsername.value").trim();
//Once dirty is set, then dont reset.
if(!this.get('enteredUsername.isDirty')) {
this.set('enteredUsername.isDirty', value.length > 0);
}
return value;
}.property('enteredUsername.value'),
usernameError: function() {
var username = this.get("username");
var isDirty = this.get('enteredUsername.isDirty');
if (!username && isDirty) {
return "please enter a username";
}
}.property('username', 'enteredUsername.isDirty')
});
Here is a working demo.

ember.js sending actions to controllers from views

I've created a typeahead view and i'm trying to send an action to the current controller to set a property. Here is my typeahead view
App.Typeahead = Ember.TextField.extend({
dataset_name: undefined, //The string used to identify the dataset. Used by typeahead.js to cache intelligently.
dataset_limit: 5, //The max number of suggestions from the dataset to display for a given query. Defaults to 5.
dataset_template: undefined, //The template used to render suggestions. Can be a string or a precompiled template. If not provided, suggestions will render as their value contained in a <p> element (i.e. <p>value</p>).
dataset_engine: undefined, //The template engine used to compile/render template if it is a string. Any engine can use used as long as it adheres to the expected API. Required if template is a string.
dataset_local: undefined, //An array of datums.
dataset_prefetch: undefined, //Can be a URL to a JSON file containing an array of datums or, if more configurability is needed, a prefetch options object.
dataset_remote: undefined, //Can be a URL to fetch suggestions from when the data provided by local and prefetch is insufficient or, if more configurability is needed, a remote options object.
ctrl_action: undefined,
didInsertElement: function () {
this._super();
var self = this;
Ember.run.schedule('actions', this, function () {
self.$().typeahead({
name: self.get('dataset_name'),
limit: self.get('dataset_limit'),
template: self.get('dataset_template'),
engine: self.get('dataset_engine'),
local: self.get('dataset_local'),
prefetch: self.get('dataset_prefetch'),
remote: self.get('dataset_remote')
}).on('typeahead:selected', function (ev, datum) {
self.selected(datum);
});
});
},
willDestroyElement: function () {
this._super();
this.$().typeahead('destroy');
},
selected: function(datum) {
this.get('controller').send(this.get('ctrl_action'), datum);
}
});
Here's an implementation
App.CompanyTA = App.Typeahead.extend({
dataset_limit: 10,
dataset_engine: Hogan,
dataset_template: '<p><strong>{{value}}</strong> - {{year}}</p>',
dataset_prefetch: '../js/stubs/post_1960.json',
ctrl_action: 'setCompanyDatum',
selected: function (datum) {
this._super(datum);
this.set('value', datum.value);
}
});
and here's my controller
App.PeopleNewController = Ember.ObjectController.extend({
//content: Ember.Object.create(),
firstName: '',
lastName: '',
city: '',
state: '',
ta_datum: undefined,
actions: {
doneEditing: function () {
var firstName = this.get('firstName');
if (!firstName.trim()) { return; }
var lastName = this.get('lastName');
if (!lastName.trim()) { return; }
var city = this.get('city');
if (!city.trim()) { return; }
var state = this.get('state');
if (!state.trim()) { return; }
var test = this.get('ta_datum');
// Create the new person model
var person = this.store.createRecord('person', {
firstName: firstName,
lastName: lastName,
city: city,
state: state
});
// Clear the fields
this.set('firstName', '');
this.set('lastName', '');
this.set('city', '');
this.set('state', '');
// Save the new model
person.save();
},
setCompanyDatum: function(datum) {
this.set('ta_datum', datum);
}
}
});
I'm expecting the setCompanyDatum controller action to be called, but it's not. Everything else is working as expected. The App.Typeahead.selected method is being called with the right action name, but it doesn't actually call the action method.
the controller inside your App.Typeahead points to the instance of the App.Typeahead, not the controller from the route where you are creating the view.
You should just be using sendAction
http://emberjs.jsbin.com/EduDitE/2/edit
{{view App.Typeahead}}
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
},
actions:{
externalAction:function(item){
console.log('helllllo' + item);
}
}
});
App.Typeahead = Ember.TextField.extend({
internalAction: 'externalAction',
didInsertElement: function () {
this.sendAction('internalAction', " I'm a sent action");
this._super();
}
});

Set controller property inside callback

I have the following controller using ember.js and the ember-auth gem. This controller works but it sets the loginErrorproperty each time I get a sign in.
BaseApp.SignInController = Auth.SignInController.extend({
email: null,
password: null,
loginError: false,
signIn: function() {
this.registerRedirect();
Auth.signIn({
email: this.get('email'),
password: this.get('password')
});
this.set('loginError', true); // Sets correctly but each time
Auth.on('signInError', function() {
console.log("This is a signin error");
});
}
});
Obviously what I would like to do is set loginError to true inside the function that is called by Auth.on like this:
BaseApp.SignInController = Auth.SignInController.extend({
email: null,
password: null,
loginError: false,
signIn: function() {
this.registerRedirect();
Auth.signIn({
email: this.get('email'),
password: this.get('password')
});
Auth.on('signInError', function() {
this.set('loginError', true); // Doesn't set the controller's property
console.log("This is a signin error");
});
}
});
But this obviously doesn't work because the scope inside the callback is different. Maybe I'm missing something very basic. How can I make it work?
The context (ie. this) is different within the anonymous function you pass to the on method than in the controller. You can get around this by saving the context to a different variable within the closure.
var self = this;
Auth.on('signInError', function() {
self.set('loginError', true); // Should now set the controller's property
console.log("This is a signin error");
});

Delete associated model with ember-data

I have two models:
App.User = DS.Model.create({
comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.create({
user: DS.belongsTo('App.User')
});
When a user is deleted, it also will delete all its comments on the backend, so I should delete them from the client-side identity map.
I'm listing all the comments on the system from another place, so after deleting a user it would just crash.
Is there any way to specify this kind of dependency on the association? Thanks!
I use a mixin when I want to implement this behaviour. My models are defined as follows:
App.Post = DS.Model.extend(App.DeletesDependentRelationships, {
dependentRelationships: ['comments'],
comments: DS.hasMany('App.Comment'),
author: DS.belongsTo('App.User')
});
App.User = DS.Model.extend();
App.Comment = DS.Model.extend({
post: DS.belongsTo('App.Post')
});
The mixin itself:
App.DeletesDependentRelationships = Ember.Mixin.create({
// an array of relationship names to delete
dependentRelationships: null,
// set to 'delete' or 'unload' depending on whether or not you want
// to actually send the deletions to the server
deleteMethod: 'unload',
deleteRecord: function() {
var transaction = this.get('store').transaction();
transaction.add(this);
this.deleteDependentRelationships(transaction);
this._super();
},
deleteDependentRelationships: function(transaction) {
var self = this;
var klass = Ember.get(this.constructor.toString());
var fields = Ember.get(klass, 'fields');
this.get('dependentRelationships').forEach(function(name) {
var relationshipType = fields.get(name);
switch(relationshipType) {
case 'belongsTo': return self.deleteBelongsToRelationship(name, transaction);
case 'hasMany': return self.deleteHasManyRelationship(name, transaction);
}
});
},
deleteBelongsToRelationship: function(name, transaction) {
var record = this.get(name);
if (record) this.deleteOrUnloadRecord(record, transaction);
},
deleteHasManyRelationship: function(key, transaction) {
var self = this;
// deleting from a RecordArray doesn't play well with forEach,
// so convert to a normal array first
this.get(key).toArray().forEach(function(record) {
self.deleteOrUnloadRecord(record, transaction);
});
},
deleteOrUnloadRecord: function(record, transaction) {
var deleteMethod = this.get('deleteMethod');
if (deleteMethod === 'delete') {
transaction.add(record);
record.deleteRecord();
}
else if (deleteMethod === 'unload') {
var store = this.get('store');
store.unloadRecord(record);
}
}
});
Note that you can specify via deleteMethod whether or not you want to send the DELETE requests to your API. If your back-end is configured to delete dependent records automatically, then you will want to use the default.
Here's a jsfiddle that shows it in action.
A quick-and-dirty way would be to add the following to your user model
destroyRecord: ->
#get('comments').invoke('unloadRecord')
#_super()
I adapted the answer of #ahmacleod to work with ember-cli 2.13.1 and ember-data 2.13.0. I had an issue with nested relationships and the fact that after deleting an entity from the database its id was reused. This lead to conflicts with remnants in the ember-data model.
import Ember from 'ember';
export default Ember.Mixin.create({
dependentRelationships: null,
destroyRecord: function() {
this.deleteDependentRelationships();
return this._super()
.then(function (model) {
model.unloadRecord();
return model;
});
},
unloadRecord: function() {
this.deleteDependentRelationships();
this._super();
},
deleteDependentRelationships: function() {
var self = this;
var fields = Ember.get(this.constructor, 'fields');
this.get('dependentRelationships').forEach(function(name) {
self.deleteRelationship(name);
});
},
deleteRelationship (name) {
var self = this;
self.get(name).then(function (records) {
if (!records) {
return;
}
var reset = [];
if (!Ember.isArray(records)) {
records = [records];
reset = null;
}
records.forEach(function(record) {
if (record) {
record.unloadRecord();
}
});
self.set(name, reset);
});
},
});
Eventually, I had to set the relationship to [] (hasMany) or null (belongsTo). Else I would have run into the following error message:
Assertion Failed: You cannot update the id index of an InternalModel once set. Attempted to update <id>.
Maybe this is helpful for somebody else.