Custom Polymer Element refresh data when visible? - polymer

In the element script I have:
Polymer({
is: 'projects-page',
attached: function () {
this.async(function () {
// access sibling or parent elements here
var model = this;
$.ajax({
url: "/api/projects",
headers: { "Authorization": "Bearer " + sessionStorage.getItem("accessToken") }
})
.done(function (data) {
console.log(data);
model.projects = data;
model.notifyPath('projects', model.projects);
})
.fail(function (jqXHR, textStatus) {
})
.always(function () {
});
});
}
});
I am needing to refresh this data when the route changes or when it becomes visible to the user.
I am still finding the Polymer docs lacking and any help would be appreciated.
UPDATE:
This is a partial answer.
How can I refresh/reload Polymer element, when page changes?

you could listen to the window url or any other variable that reflects the state of your application with a change-event listener and reload your ajax then. The model should be turned into a properity of your projects-page and the ajax-done event listener should use the Polymer-set function. So the view gets repopulated without any big hazzle.
https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#set-path
https://www.polymer-project.org/1.0/docs/devguide/properties.html#change-callbacks

Related

How to completely disable the cache in AngularJS

I use a form to submit values. When I click on the submit button, it calls edit().
Values are stored in the database (with php/mysql). Everything works fine so far.
I retrieve the values on the same partial view. On window.location.reload(); the page will refresh but the values are not instantly updated. After several refresh, it's
(When my DevTools is open, the cache is disable... so it's instantly updated)
Without the DevTools open, the cache works even if I put some function to disable the cache.
listingProjectApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
listingProjectApp.factory('EditCache', function($cacheFactory) {
return $cacheFactory('editCache', {
capacity: 1
});
});
listingControllers.controller('editProjectCtrl', ['$scope', '$http', '$routeParams', 'EditCache',
function ($scope, $http, $routeParams, EditCache) {
var result = EditCache.get('$http');
if( result ){
$scope.project = result;
console.log("Results from cache");
}
else {
$http({
url: "php/getProjectDetails.php",
method: "GET",
cache: false,
params: { 'id': $scope.projectId }
}).success(function(data) {
$scope.project = data;
EditCache.put('$http', data);
console.log("New results");
});
}
console.log(EditCache.info())
$scope.edit = function(project){
console.log(project);
$http({
url: "php/edit.php",
method: "POST",
data: project
}).success(function(id) {
EditCache.removeAll();
window.location.reload();
});
return false;
}
}]);
Looks like it's not the AngularJS cache's fault, but rather the browser's: for the browser, your XHR requests are simple HTTP GET requests, and all caching policies are applied to them. To avoid caching the partials, you'll have to either tweak your back-end to send appropriate headers to forbid caching, or use the old random suffix trick: add another dummy parameter to your params (like dummy: 'some-random-string'). This way, every GET request will be unique, and you'll not hit the cache.

Cannot view source HTML on Chrome

I am unable to view the HTML content of web pages when I view source in Google Chrome's dev tools. For example, if I view the source of https://stackoverflow.com/help, the only content I can see is as follows.
<script>
$('#herobox li').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
window.location.href = '/about';
});
$('#tell-me-more').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
});
$('#herobox #close').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("hero.action", { hero_action_type: "minimize" }, true);
});
$.cookie("hero", "mini", { path: "/" });
$.ajax({
url: "/hero-mini",
success: function (data) {
$("#herobox").fadeOut("fast", function () {
$("#herobox").replaceWith(data);
$("#herobox-mini").fadeIn("fast");
});
}
});
return false;
});
</script>
I'm not sure if I've inadvertently changed a setting in Chrome, but any help would be greatly appreciated.
I'm using chrome Version 29.0.1547.76.
I have disabled all extensions.
I tried this using a new profile with the same effect.
I'm not behind a proxy.
If you open the DevTools after loading the page, the content of the items listed on the Resources tab may not be populated. This is also true of network requests on the Network tab. To see the fully populated resources on the Resources tab, first open the DevTools, then refresh the page, or navigate to the desired page with the DevTools open. Now select the html resource and it should be populated.

How to fetch a specific div id from an html file through ajax

I have two html files called index.html & video.html
video.html holds coding like:
<div id="video">
<iframe src="http://www.youtube.com/embed/tJFUqjsBGU4?html5=1" width=500 height=500></iframe>
</div>
I want the above mentioned code to be crawled from video.html page from index.html
I can't use any back-end coding like php or .net
Is there any way to do using Ajax?
Try this...
$.ajax({
url: 'video.html',
success: function(data) {
mitem=$(data).filter('#video');
$(selector).html(mitem); //then put the video element into an html selector that is on your page.
}
});
For sure,send an ajax call.
$.ajax({
url: 'video.html',
success: function(data) {
data=$(data).find('div#video');
//do something
}
});
Yep, this is a perfect use case for ajax. When you make the $.ajax() request to your video.html page, you can then treat the response similar to the way you'd treat the existing DOM.
For example, you'd start the request by specifying the URI in the the following way:
$.ajax({
url: 'video.html'
})
You want to make sure that request succeeds. Luckily jQuery will handle this for you with the .done callback:
$.ajax({
url: "video.html",
}).done(function ( data ) {});
Now it's just a matter of using your data object in a way similar to the way you'd use any other jQuery object. I'd recommend the .find() method.
$.ajax({
url: "video.html",
}).done(function ( data ) {
$(data).find('#video'));
}
});
Since you mentioned crawl, I assume there is the possibility of multiple pages. The following loads pages from an array of urls, and stores the successful loads into results. It decrements remainingUrls (which could be useful for updating a progressbar) on each load (complete is called after success or error), and can call a method after all pages have been processed (!remainingUrls).
If this is overkill, just use the $.ajax part and replace myUrls[i] with video.html. I sepecify the type only because I ran into a case where another script changed the default type of ajax to POST. If you're loading dynamic pages like php or aspx, then the cache property might also be helpful if you're going to call this multiple times per session.
var myUrls = ['video1.html', 'video2.html', 'fail.html'],
results = [],
remainingUrls;
$(document).ready(function () {
remainingUrls = myUrls.length;
for (var i = 0, il = myUrls.length; i < il; i++) {
$.ajax({
url: myUrls[i],
type: 'get', // somebody might override ajax defaults
cache: 'false', // only if you're getting dynamic pages
success: function (data) {
console.log('success');
results.push(data);
},
error: function () {
console.log('fail');
},
complete: function() {
remainingUrls--;
if (!remainingUrls) {
// handle completed crawl
console.log('done');
}
}
});
}
});
not tested, but should be something similair to this: https://stackoverflow.com/a/3535356/1059828
var xhr= new XMLHttpRequest();
xhr.open('GET', 'index.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementsByTagName('html').innerHTML= this.responseText;
};
xhr.send();

Firing a javascript function from a dynamically created button

Updated code and issue:
I am creating a test harness for my RPC server. Currently it consists of a page which immeadiately fires off an AJAX request to retrieve all functions on the server. Once that is returned it creates a list of buttons so I can click to test. Eventually I will add dialog boxes to test parameter passing to the functions but currently I want to just fire off the basic request when I click the button. The issue I am seeing is that the onclick function is always firing the last function in the list presumably because when the click is fired key is set to the last value in the array. I thought to pass button.innerHTML value but that too suffers that the last button.innerHTML is that of the final key.
What do I need to do to fire off the action correctly?
Here is the business end of the code:
$(document).ready(function() {
$.jsonRPC.setup({
endPoint: '//api.localhost/index.php'
});
$.jsonRPC.request('getExampleData', {
params: [],
success: function(result) {
for (var key in result.result) {
console.log(key+' => '+result.result[key]);
var button = document.createElement('button');
button.innerHTML = result.result[key];
button.onclick = function() { callRPCFunction(result.result[key]); return false; }
var foo = document.getElementById("page");
foo.appendChild(button);
}
},
error: function(result) {
console.log(result);
}
});
});
function callRPCFunction(target) {
$.jsonRPC.request(target, {
params: [],
success: function(result) {
console.log(result);
},
error: function(result) {
console.log(result);
}
});
}
Assignment to element.onClick will not work until the element is added to the DOM. You may call element.onClick(callRPCFunction(result.result[key])); after foo.appendChild(element);. That might work!
You may use jQuery's live() here, it was created for these purposes:
$(element).live('click', callRPCFunction(result.result[key])

submit form using mootools

I have made a class that handles load and submit of a html form. See code below
ND.Form = new Class({
//--- Implements options og events.
Implements: [Options, Events],
//--- Options.
options: {
url: '',
injectTo: ''
},
//--- Initialize the class.
initialize: function (panel, options) {
//--- Set options
this.setOptions(options);
this.panel = panel;
this.loadForm();
},
loadForm: function () {
var req = new Request.HTML({
url: this.options.url,
method: 'get',
onSuccess: function (html) {
$(this.options.injectTo).empty();
$(this.options.injectTo).adopt(html);
var formId = $(this.options.injectTo).getFirst('form').get('id');
$(formId).addEvent('submit', function (e) {
e.stop();
this.submitForm(formId);
} .bind(this));
} .bind(this)
}).send();
},
submitForm: function (formId) {
$(formId).set('send', {
onSuccess: function (resp) {
this.panel.loadContent();
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}.bind(this),
onFailure: function (resp) {
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}
});
$(formId).send();
}
});
And it all works just fine, exept that when i push the save button more than ones the "this.panel.loadContent();" in the "submitForm: function (formId)" fires the same x amount of times I have pushed the button, how can i prevent this ?
/Martin
Starting from mootools 1.3 "set('send')" adds another one event.
So You need to write:
$('myForm').set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
}).addEvent('submit', function(e){
e.stop();
this.send();
});
instead of:
$('myForm').addEvent('submit', function(e){
e.stop();
this.set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
});
}).send();
Then Request will be sent only once each time when You handle form.
Basically we need to do three things:
Listen for the ‘click’ event on the submit button.
Stop the event from submitting the form.
Send the form using $(formElement).send()
A solution could look something like this:
$('submit').addEvent( 'click', function(evt){
// Stops the submission of the form.
new Event(evt).stop();
// Sends the form to the action path,
// which is 'script.php'
$('myForm').send();
} );
I have used the request.send() method but googled trying to find a way to just replicate the action of a user hitting a form submit button, but with also allowing some javascript logic being performed beforehand. I did not find anything in discussions specifically addressing this. The answer I found is to use the form.submit() method.