Accessing controller properties within controller function in ember - ember.js

I'm unable to access the controller property within a controller function:
App.ViewRController = Ember.Controller.extend({
datas:null,
actions:{
viewfile:function() {
let filename = this.get('filename');
let count=0;
let data;
let self = this;
if (filename != null)
{
filename = filename.trim();
if(filename.length > 0)
{
try {
let obj= new XMLHttpRequest();
obj.onreadystatechange = function() {
if(obj.readyState==4 && obj.status ==200)
{
let json = obj.responseText;
console.log(self);
data = JSON.parse(json);
self.set(datas, data);
}
}
let params = "filename=" + filename;
obj.open("POST","view");
obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
obj.send(params);
//this.set('datas',data);
}
catch(e)
{
alert(e);
}
}
else
alert("enter filename");
}
else
alert("enter filename");
}
}
The template should iterate over the data object with properties. But I couldn't set the data property within the function in the controller.

You trying to set a property with
self.set(datas,data);
But you need to be setting the "datas" property as a string:
self.set("datas", data);

Related

How to share post in facebook by using Xamarin Forms

I'm currently working on Xamarin and I'm confused with the facebook sharing option in xamarin forms particularly in Xamarin Android the IOS code is
public void ShareOnFacebook(IFacebookDelegate pDele)
{
string[] perm = {"publish_actions"};
if (AccessToken.CurrentAccessToken == null || !AccessToken.CurrentAccessToken.HasGranted("publish_actions"))
{
UIViewController mainController = UIApplication.SharedApplication.KeyWindow.RootViewController;
_manager.LogInWithPublishPermissions(perm, mainController, (result, error) =>
{
if (error != null || result.IsCancelled)
{
}
else {
ShareNow();
}
});
} else {
ShareNow();
}
}
The only thing which stops me is Xamarin Android facebook post sharing.
Can anyone modify this code according to Xamarin Android Or share his/her own code .
I have implemented share for twitter and fb .
iOS version
you can share using native social services from ios and if not available use
OAuth2Authenticator to get access token then post using FB graph
public void ShareViaSocial(string serviceType, string urlToShare)
{
socialKind = serviceType == "Twitter" ? SLServiceKind.Twitter : SLServiceKind.Facebook;
if (SLComposeViewController.IsAvailable(socialKind))
{
_socialComposer = serviceType == "Twitter" ? SLComposeViewController.FromService(SLServiceType.Twitter) : SLComposeViewController.FromService(SLServiceType.Facebook);
_socialComposer.AddUrl(new Uri(urlToShare));
viewController.PresentViewController(_socialComposer, true, () =>
{
_socialComposer.CompletionHandler += (result) =>
{
Device.BeginInvokeOnMainThread(() =>
{
viewController.DismissViewController(true, null);
if (result == SLComposeViewControllerResult.Done)
{ OnShare(this, ShareStatus.Successful); }
else
{ OnShare(this, ShareStatus.NotSuccessful); }
});
};
});
}
//If user doest have fb app and no credential for social services we use fb graph
else if (socialKind == SLServiceKind.Facebook)
{
var auth = new OAuth2Authenticator(
clientId: SharedConstants.FacebookLiveClientId,
scope: SharedConstants.FacebookScopes,
authorizeUrl: new Uri(SharedConstants.FacebookAuthorizeUrl),
redirectUrl: new Uri(SharedConstants.FacebookRedirectUrl));
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
//hide the webpage after completed login
viewController.DismissViewController(true, null);
// We presented the UI, so it's up to us to dimiss it on iOS.
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
//If user doest have twitter app and no credential for social services we use xanarub auth for token and call twitter api for sending tweets
else
{
var auth = new OAuth1Authenticator(
SharedConstants.TwitterConsumerKey,
SharedConstants.TwitterConsumerSecret,
new Uri(SharedConstants.TwitterRequestUrl),
new Uri(SharedConstants.TwitterAuth),
new Uri(SharedConstants.TwitterAccessToken),
new Uri(SharedConstants.TwitterCallBackUrl));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
viewController.DismissViewController(true, null);
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
}
}
Android version
You can use native facebook ShareDialog and if isn't available use OAuth2Authenticator to get access token then post using FB graph
and using OAuth1Authenticator for posing on twitter
public void ShareViaSocial(string serviceType, string urlToShare)
{
ShareDialog di = new ShareDialog(MainActivity.Instance);
var facebookShareContent = new ShareLinkContent.Builder();
facebookShareContent.SetContentUrl(Android.Net.Uri.Parse(urlToShare));
if (serviceType == "Facebook")
{
if (di.CanShow(facebookShareContent.Build(), ShareDialog.Mode.Automatic))
{
di.Show(facebookShareContent.Build());
}
else
{
var auth = new OAuth2Authenticator(
clientId: 'ClientId',
scope: "public_profile,publish_actions",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri( "http://www.facebook.com/connect/login_success.html"));
MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
}
else
{
var auth = new OAuth1Authenticator(
'TwitterConsumerKey',
'TwitterConsumerSecret',
new Uri("https://api.twitter.com/oauth/request_token"),
new Uri("https://api.twitter.com/oauth/authorize"),
new Uri("https://api.twitter.com/oauth/access_token"),
new Uri('TwitterCallBackUrl'));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));
}
}

Ember: Setting a component object value within a promise

I have component with a couple of properties, using a promise in the willRender hook to try and create a (pagination) object:
export default Ember.Component.extend({
pagination:null,
testing:null, // to check if this.set is ok within the promise!
willRender() {
let page = {};
let model = this.get('data');
model.get('products').then(relatedItems => {
let maxRecords = relatedItems.get('length');
relatedItems.forEach(function(item,index) {
if (item.get('slug') === itemModel.get('id')) {
if (index === 0) {
page.Prev = null;
page.Next = relatedItems.objectAt(index+1).get('slug');
}
else if (index+1 === maxRecords) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
page.Next = null;
}
else {
page.Prev = relatedItems.objectAt(index-1).get('slug');
page.Next = relatedItems.objectAt(index+1).get('slug');
}
}
});
this.set('testing','hello world');
console.log(this.get('testing')); // hello world
this.set('pagination',page);
console.log(this.get('pagination')); // Object {Prev: "product-1", Next: "product-2"}
},reject => {
console.log('error '+reject);
});
}
})
In my template
{{testing}} // prints hello world
However, if I try and access {{pagination}} eg {{log pagination}}, the browser crashes with a loop printing out the object to the console.
I don't know where I'm going wrong here - any help much appreciated!
It's likely you are triggering the template to rerender causing willRender to fire over and over which causes an infinite loop in your code.
willRender is a non-standard place to do this code, init would be more standard since it only fires on initialization of the component. Even better would be to use
myInit: Ember.on('init', function(){
....
})`
instead of overriding willRender on the object.
try to check whether Object is present at specific position. i think its going undefined during iteration of for loop. try to ensure that ObjectAt is not returning undefined or null value during running of for loop.
relatedItems.forEach(function(item,index) {
if (item.get('slug') === itemModel.get('id')) {
if (index === 0) {
page.Prev = null;
if(relatedItems.objectAt(index+1) ! = undefined) {
page.Next = relatedItems.objectAt(index+1).get('slug');
}else{
page.Next == null;
}
}
else if (index+1 === maxRecords) {
if(relatedItems.objectAt(index-1) ! = undefined) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
}else{
page.Prev = null;
}
page.Next = null;
}
else {
if(relatedItems.objectAt(index-1) ! = undefined) {
page.Prev = relatedItems.objectAt(index-1).get('slug');
}else{
page.Prev = null;
}
if(relatedItems.objectAt(index+1) ! = undefined) {
page.Next = relatedItems.objectAt(index+1).get('slug');
}else{
page.Next = null;
}
}
}
Please ensure that Object at is returning object.
There seems to be a few problems here, would be interested to know what your console errors are.
You don't seem to have defined itemModel so don't know how you're referencing that.
Also you can't access this from within a .then. You need to do something like this to set a component variable.
var _this = this;
promise().then(function(results) {
_this.set('testing', 'hello world');
});
you are not using , after testing:null
there should be , after testing property like that
pagination:null,
testing:null, // i use ',' after testing: null property
try to use your pagination code under init hook rather than willrender hook
init() {
//you code
},

How to properly setup a store that acts as a single pointer across your web app

I have a home grown store that has a simple identityMap. When I return an array of models from this and bind it to a controllers "model" it reflects what you'd expect
the first time you hit a route it reflects this in the template as
you'd expect
But later if I get this same store instance (it's a singleton) and push an object into the identityMap it doesn't automatically update the previous template
The store itself is super basic (no relationships/ just push objects and get by id)
function buildRecord(type, data, store) {
var containerKey = 'model:' + type;
var factory = store.container.lookupFactory(containerKey);
var record = factory.create(data);
var id = data.id;
identityMapForType(type, store)[id] = record;
return record;
}
function identityMapForType(type, store) {
var typeIdentityMap = store.get('identityMap');
var idIdentityMap = typeIdentityMap[type] || {};
typeIdentityMap[type] = idIdentityMap;
return idIdentityMap;
}
var Store = Ember.Object.extend({
init: function() {
this.set('identityMap', {});
},
push: function(type, data) {
var record = this.getById(type, data.id);
if (record) {
record.setProperties(data);
} else {
record = buildRecord(type, data, this);
}
return record;
},
getById: function(type, id) {
var identityMap = identityMapForType(type, this);
return identityMap[id] || null;
}
getEverything: function(type) {
var identityMap = identityMapForType(type, this);
var keys = Object.keys(identityMap);
var values = [];
for (var i = 0; i < keys.length; i++)
{
var val = identityMap[keys[i]];
values.push(val);
}
return values;
}
});
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(container, application) {
application.register('store:main', Store);
application.inject('controller', 'store', 'store:main');
application.inject('route', 'store', 'store:main');
}
});
});
In my model hook (in the find all route lets say) I simply query for each item and push them into the store
//inside my model find method lets say ...
find: function(store) {
var url = "/api/foo";
$.getJSON(url, function(response) {
response.forEach(function(data) {
var model = store.push("foo", data);
}
}
return store.getEverything("foo");
}
So I assumed my controllers' model was this bound array (using a single pointer in memory for this array of models)
Yet when I do this inside a controller submit action it won't re-render that prev view (to show the new item that was added to that store's array)
actions: {
submit: function() {
var foo = {}; // assume this is a real json response or js object
var store = this.get("store");
store.push("foo", foo);
}
}
Because of this today, I'm forced to get the parent controller and "set" / "push" this new object to it's content/model property :(
Anyone know what I'm doing wrong here?
I like homegrown solutions, they generally are easier to work with and meld around what you're working on.
So I'm actually surprised this part is working:
//inside my model find method lets say ...
find: function(store) {
var url = "/api/foo";
$.getJSON(url, function(response) {
response.forEach(function(data) {
var model = store.push("foo", data);
}
}
return store.getEverything("foo");
}
If I read through it I see you make an ajax call, and then return store.getEverything immediately after (without a guarantee that the ajax call has completed). Then inside of getEverything you create a new array called values then iterate the identity map linking up all of the currently available records and return that. At this point your store is unaware of this array going forward. So any changes to your store wouldn't get pushed out to the array, they might make it into the identity map, but it isn't feeding the getEverything array.
There are a couple of solutions, one would be to keep track of your everything array. That collection would be super cheap to build, more expensive to search, so keeping the identity map as well would be super beneficial. You could follow your same pattern, but one collection would be the map, whereas the other would be an array of everything.
Modified Build Record
function buildRecord(type, data, store) {
var containerKey = 'model:' + type;
var factory = store.container.lookupFactory(containerKey);
var record = factory.create(data);
var id = data.id;
identityMapForType(type, store)[id] = record;
everythingArrayForType(type, this).pushObject(record);
return record;
}
Copy paste, possibly could be refactored
function everythingArrayForType(type, store) {
var everythingArrays = store.get('everythingArrays');
var arr = everythingArrays[type] || [];
everythingArrays[type] = arr;
return arr;
}
Slightly modified Store
var Store = Ember.Object.extend({
init: function() {
this.set('identityMap', {});
this.set('everythingArrays', {});
},
push: function(type, data) {
var record = this.getById(type, data.id);
if (record) {
record.setProperties(data);
} else {
record = buildRecord(type, data, this);
}
return record;
},
getById: function(type, id) {
var identityMap = identityMapForType(type, this);
return identityMap[id] || null;
}
getEverything: function(type) {
return everythingArrayForType(type, this);
}
});

Ember Data: How to make AJAX calls in Ember-Objects (has no method 'find' )

I'm trying to make an AJAX call to my API over Ember Data (1.0.0 Beta 4), but I don't know how to access the model outside the router. The documentation provides such examples only:
App.PostRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('post', params.post_id);
}
});
My code:
var AuthManager = Ember.Object.extend({
authenticate: function(accessToken, userId) {
var user = this.store.find('user', userId);
/* ... */
},
/* ... */
});
Now I get has no method 'find':
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
if (typeof properties !== 'object' && properties !== undefined) {
throw new Ember.Error("Ember.Object.create only accepts objects.");
}
if (!properties) { continue; }
var keyNames = Ember.keys(properties);
for (var j = 0, ll = keyNames.length; j < ll; j++) {
var keyName = keyNames[j];
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
In Ember Data < 0.14 methods like App.User.find(id) were present but it's deprecated
You can use the dependency injection to inject a store in the AuthManager:
Ember.Application.initializer({
name: "inject store in auth manager",
initialize: function(container, application) {
// register the AuthManager in the container
container.register('authManager:main', App.AuthManager);
// inject the store in the AuthManager
container.injection('authManager', 'store', 'store:main');
// inject the AuthManager in the route
container.injection('route', 'authManager', 'authManager:main');
// inject in the controller
// container.injection('controller', 'authManager', 'authManager:main');
}
});
And in the route you will able to do:
App.IndexRoute = Ember.Route.extend({
model: function() {
this.authManager.authenticate('token', 'userId');
return [];
}
});
See this in action http://jsfiddle.net/marciojunior/3dYnG/

How to update record in local storage using ember data and localstorage adapter?

I am new to emberjs and making one simple CRUD application. I am using ember data and localstorage-adapter to save record in local storage of browser.
I am trying to update record using localstorage-adapter but it is throwing error.
I have listed my code here :
updatecontact: function(){//save data in local storage
var fname = this.obj_form_edit_data.get('cont_data.fname');
var lname = this.get('cont_data.lname');
var email = this.get('cont_data.email');
var contactno = this.get('cont_data.contactno');
var gendertype = ((this.get('isMale') == true) ? true : false);
var contactype = $(".selectpicker").val();
Grid.ModalModel.updateRecords({
fname: fname,
lname: lname,
email: email,
contactno: contactno,
gendertype: gendertype,
contactype: contactype
});
this.get('store').commit();
}
I am getting following error using above code :
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this);
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
delete m.proto;
finishChains(this);
this.init.apply(this, arguments);
} has no method 'updateRecords'
I am using following code to create new record which working fine :
savecontact: function(){//save data in local storage
var fname = this.obj_form_edit_data.get('cont_data.fname');
var lname = this.obj_form_edit_data.get('cont_data.lname');
var email = this.obj_form_edit_data.get('cont_data.email');
var contactno = this.obj_form_edit_data.get('cont_data.contactno');
var gendertype = ((this.get('isMale') == true) ? true : false);
var contactype = $(".selectpicker").text();
Grid.ModalModel.createRecord({
fname: fname,
lname: lname,
email: email,
contactno: contactno,
gendertype: gendertype,
contactype: contactype
});
this.get('store').commit();
}
You're using updateRecords as a plural, it should be updateRecord