this.get_element() of asp.net ajax is not working in functions I declare - asp.net

I try to access the element in my own function through this.get_element() but it does not work.
Type.registerNamespace("LabelTimeExtender1");
LabelTimeExtender1.ClientBehavior1 = function(element) {
LabelTimeExtender1.ClientBehavior1.initializeBase(this, [element]);
var testelement=this.get_element();
var timestamp= this.get_element().attributes['TimeStamp'].value;
alert("in constructor");
},
LabelTimeExtender1.ClientBehavior1.prototype = {
initialize: function() {
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'initialize');
setInterval (this.timer,1000);
alert("after");
},
dispose: function() {
//Add custom dispose actions here
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'dispose');
},
timer: function(){
debugger;
var date= new Date(this.timestamp);
var datenow= new Date ();
this._element.innerText=" ";
if(date.getUTCFullYear<datenow.getUTCFullYear)
{
var myelement= this.get_element();
myelement .innerHTML= date.getUTCFullYear.toString();
}
if(date.getUTCMonth<datenow.getUTCMonth)
{
this.get_element().innerHTML=date.getUTCMonth.toString();
}
if(date.getUTCDay<datenow.getUTCDay)
{
this.get_element().innerHTML=date.getUTCDay.toString();
}
if(date.getUTCHours <datenow.getUTCHours )
{
this.get_element().innerHTML=date.getUTCHours .toString();
}
if(date.getUTCMinutes<datenow.getUTCMinutes)
{
this.get_element().innerHTML=date.getUTCMinutes.toString();
}
}
}
LabelTimeExtender1.ClientBehavior1.registerClass('LabelTimeExtender1.ClientBehavior1', Sys.UI.Behavior);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
Here I am trying to access the custom attribute 'TimeStamp' and calcutate the time and assign to the label to show.

Try to invoke your function through delegates.Then you will not have problem with [this] keyword
something like this:
setInterval (Function.createDelegate(this, this.timer),1000)

Related

Create a universal helper variable

Is there a way to create a variable at the top of template helpers to remove duplication.
In this particular situation I'm using var candidate = FlowRouter.getParam('id'); and I have to create the variable in each helper. I assume there is a better way.
professionalOverview: function() {
var candidate = FlowRouter.getParam('id');
return ProfessionalOverview.findOne({ candidateUserId: candidate });
},
candidateImg: function() {
var candidateUserId = FlowRouter.getParam('id');
return Files.findOne({ userId: candidateUserId });
},
EDIT
Template.talentProfileNew.onCreated(function() {
var self = this;
self.autorun(function(){
this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
}
});
Template.talentProfileNew.helpers({
candidate: function() {
console.log(Template.instance().candidateUserId.get());
return Meteor.users.findOne({_id: Template.instance().candidateUserId.get()});
}
});
you could read it once in onCreated() and put it in a reactive var. e.g.
Template.Foo.onCreated(function() {
this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
});
Template.Foo.helpers({
candidateImg() {
return ProfessionalOverview.findOne({ userId: Template.instance().candidateUserId.get()});
}
});

How to return "then()" method in angularjs?

My case:
app.js:
let app = angular.module('myApp', []);
app.controller('login', function ($scope, $login) {
$scope.account = {};
$scope.loginForm_submit = function ($event, account) {
$event.preventDefault();
if ($login.isValid(account)) {
$login.submit(account);
// goal:
$login.submit(account).then(function () {
window.location = '/'
}, function (msg) {
console.log(msg)
});
}
};
});
login.js:
app.factory('$login', function () {
let o = {
isValid: function (x) {
let success = false;
// validating...
return success
},
submit: function (x) {
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
// return then() with successCallback() function
} else {
let msg = data['ErrorMessage'];
// return then() with errorCallback() function
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
}
}
return o
});
data is an object like:
let data = {
'Success': false,
'ErrorMessage': 'Invalid login attempt.'
};
I want to return then() method after submitting to access result. How can I do that?
UPDATE:
In controller:
[HttpPost]
public async Task<ObjectResult> Login(LoginViewModel model)
{
IDictionary<string, object> value = new Dictionary<string, object>();
value["Success"] = false;
if (ModelState.IsValid)
{
// login
value["Success"] = true;
}
return new ObjectResult(value);
}
First of all, you should avoid using $ for your own functions.
About your problem, you need to use $q. And you should use what angular offers to you.
Let me give you this :
app.factory('loginFactory', function($q, $http) {
var ret = {
isValid: isValid,
submit: submit
}
return ret;
function isValid(x) {
// Your code ...
return false;
}
function submit(x) {
// x is your form data, assuming it's a JSON object
var deferred = $q.defer();
// Assuming you're posting something
$http.post('yoururl', x,{yourConfigAsAnObject: ''})
.then(function(success){
console.log(success.data);
deferred.resolve(success.data);
}, function(error) {
console.log(error);
deferred.reject(error);
});
return deferred.promise;
}
});
Now, in your controller, you can use
loginFactory.submit(yourParam).then(function(success){
// Your code
}, function(error) {
// Your code
});
app.factory('$login', function ($q) {
let o = {
isValid: function (x) {
let success = false;
// validating...
return success
},
submit: function (x) {
var d = $q.defer();
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
// return then() with successCallback() function
d.resolve('success');
} else {
let msg = data['ErrorMessage'];
d.reject(msg);
// return then() with errorCallback() function
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
else {
d.reject('error');
}
return d.promise;
}
}
return o
});
dude,I made a sample function with promise
$q should be injected as dependency
class AppUserService {
constructor($http,CONFIG_CONSTANTS,$q, AuthService) {
this.API_URL = CONFIG_CONSTANTS.API_URL;
this.$http = $http;
this.$q = $q;
this.api_token = AuthService.api_token;
}
getAppUserList() {
const deferred = this.$q.defer();
this.$http.get(`${this.API_URL}/customer?api_token=${this.api_token}`)
.success(response => deferred.resolve(response))
.error(error => deferred.reject(error));
return deferred.promise;
}
}
its in ES6 form.
How to use:
AppUserService.getAppuserList().then(success => {
// code for success
},error => {
// code for error
})
submit: function (x) {
return $q(function (resolve, reject) {
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
resolve(data);
// return then() with successCallback() function
} else {
let msg = data['ErrorMessage'];
reject(msg);
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
else
reject('x not valid');
}
}
}
But I recommended to use angular $http service.

Meteor. Problems with subscribe/publish

i have a problem.
I'm trying to build highcharts graphic.
How it works:
I'm going to my route ('ship.details'), and here i have not problems.
My problem:
subsription to (ships_snapshots_all) not working.
My publish.js:
Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
}
});
Meteor.publish("ships_snapshots_all", function() {
return ships_snapshots.find({});
})
My subscribe.js (in lib folder):
Meteor.subscribe('ships_snapshots');
Meteor.subscribe('ships_snapshots_all');
Problem 100% in my subsription, because if i'm installing autopublish all working good. And problem in my router i think.
router.js:
Router.route('/ships/details', {
name: 'ship.details',
loadingTemplate: 'loading',
onBeforeAction: function() {
var shipId = Session.get('currentShipId');
if(!shipId) {
Router.go('user.ships');
} else {
this.next();
}
},
waitOn: function() {
if (Meteor.isClient) {
var getCompare = Meteor.user().profile.wows.compareWith;
console.log(getCompare);
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
var user2Id = user2._id;
if (getCompare) {
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
if (user2) {
var user2Id = user2._id;
}
}
if (getCompare) {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id) && Meteor.subscribe('userSearchInfo', getCompare);
Session.set('compareWith', user2);
console.log('user2 _____');
console.log(user2);
return handle
} else {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id);
return handle
}
}, data: function() {
if (handle.ready()) {
var shipname = this.params.shipName;
var obj = {};
var query = ships.findOne();
var shipId = Session.get('currentShipId');
var result;
_.each(Meteor.user().profile.wows.ships, function(row) {
if (row.ship_id === shipId) {
result = row;
}
});
return result;
}
}
});
I think my problem in subscripion for ship_snapshots. Something going wrong here, but i can't to resolve this problem.
What exactly do you mean by "not working"? From your code I would assume that you're always seeing all the ship snapshots.
You shouldn't have the subscribes in /lib if you have them in your router. If you have Meteor.subscribe('ships_snapshots_all'); in /lib then you should always be seeing all the ship snapshots (assuming you're not stopping that subscription anywhere).
Also your subscription to all should be:
Meteor.publish("ships_snapshots", function(user, options) {
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
} else this.ready();
});
You don't want to return null when there is no user, you can just mark the subscription as ready without finding any records. This is not the cause of your problem but just good practice.
Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user._id}, options);
}
});
In your publish script, is user really an id or is it a user object? I changed it to user._id. Please check that.

How to Call Pagemethod in Angular js Service

i am new in Angular js.
Static Method in Code Behind
[WebMethod]
public static string GetPracticeLocations()
{
return "[{ id: 1, name: Test AccountName}]";
}
Angular JS Service
appSettings.service('PracticeLocationsService', function () {
this.getPracticeLocations = function () {
var PracticeLocationsData = PageMethods.GetPracticeLocations();
return PracticeLocationsData;
};
});
i want to know how to implement page method in Angular JS.
Any helpful suggustein apricited
Thanks
Probably I'm too late, but you could use defer to call a page method and return a promise,
var getPracticeLocations = function () {
var deferred = $q.defer();
PageMethods.GetPracticeLocations(function (response) {
if (response) {
deferred.resolve({ result: angular.fromJson(response) });
} else {
deferred.resolve({ result: null });
}
},
function (msg, code) {
deferred.reject(msg);
});
return deferred.promise;
};
You want to look at factory() and $http
pseudo code:
angular.factory("PageMethods", ["$http", function($http){
return {
GetPracticeLocations : function(){
return $http.get("/someurl");
}
}
}]);

Write ClientSide code from Custom ASP .NET Extender server side ExtenderControlBase

I'm extending ExtenderControlBase control in ASP .NET. It's called:
public class LookupExtender : ExtenderControlBase
Basically what it doest in something similar to autocomplete function - but static. LookupExtender has TypeName & ListName attritbutes that specify:
class that has string[] GetList(string listName) method
name of the list that will be passed to GetList method
And now, LookupExtender creates TypeName instance on the fly (reflection), calls GetList method and I would like to render string[] result to client side as array, so that extender client-side code has static source for autosuggestion.
Is there any way to render JavaScript from LookupExtender class?
This is my sample code (currently autosuggestion values are hardcoded):
set_TargetTextBoxID: function (value) {
this._targetTextBoxID = value;
$(function () {
var availableTags = [
"Switzerland",
"Poland",
"Europe",
"USA",
"Asia"
];
$("#" + value).autocomplete({
source: availableTags,
minLength: 0,
close: function () {
$(this).blur();
}
}).focus(function () {
$(this).autocomplete("search", "");
});
});
}
Turned out to be pretty easy
server side of extender:
protected override void RenderInnerScript(ScriptBehaviorDescriptor descriptor)
{
var listSource = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(SourceType) as ILookupExtenderListSource;
if (listSource == null) return;
var lookupList = listSource.GetList(SourceList);
descriptor.AddProperty("LookupArray", lookupList);
}
client side js script:
CIPNet.Extenders.LookupBehavior.prototype = {
initialize: function() {
CIPNet.Extenders.LookupBehavior.callBaseMethod(this, 'initialize');
},
dispose: function() {
CIPNet.Extenders.LookupBehavior.callBaseMethod(this, 'dispose');
},
//
// Property accessors
//
get_LookupArray: function() {
return this._lookupArray;
},
set_LookupArray: function(value) {
this._lookupArray = value;
},
get_TargetTextBoxID: function() {
return this._targetTextBoxID;
},
set_TargetTextBoxID: function(value) {
this._targetTextBoxID = value;
var that = this;
$(function() {
var showSuggestion = function () {
$(this).autocomplete("search", "");
};
var availableTags = that._lookupArray;
$("#" + value).autocomplete({
source: availableTags,
delay: 0,
minLength: 0
}).click(showSuggestion);
});
}
};

Resources