I have a Kendo grid with multiple columns, but I want to display the Name of the Doc and when I click it to get the path of that Doc.
View
columns.Bound(od => od.DocumentListName).Width(150).ClientTemplate("#=generateTemplate(DocumentListName)#");
JavaScript function that displays the list of Docs
function generateTemplate(DocumentList) {
var template = "<ul>"
if (DocumentList == null || DocumentList == undefined) {
template = template + "<li>N/A</li>";
} else {
for (var i = 0; i < DocumentList.length; i++) {
template = template + "<li>" + DocumentList[i] + "</li>";
}
}
return template + "</ul>";
}
And my ActionResult
public ActionResult GetDocuments(ViewModel VM)
{
using (var db = new DB())
{
var docName = db.Documents.Include("Doc").Where(x => x.Id == VM.Id).Select(z => z.Name).ToList();
if (docName.Count() != 0) {
}
Vm.DocumentListName = docName;
var docPath = db.Documents.Include("Doc").Where(x => x.Id == Vm.Id).Select(z => z.Path).ToList();
VM.DocumentPathList = docPath;
return Json(VM, JsonRequestBehavior.AllowGet);
}
}
I know I can display the Path as ActionLink this way
columns.Template(#<text>#Html.ActionLink(#item.DocumentPathList.ToString(), "GetDocuments", "Controller") </text>).ClientTemplate("<a href='#=DocumentPathList#</a>").Title("Docs");
But how can I combine them?
function generateTemplate(DocumentList) {
var template = "<ul>";
if (DocumentList == null || DocumentList == undefined) {
template = template + "<li> </li>";
} else {
for (var i = 0; i < DocumentList.length; i++) {
var url = '#Url.Action("DownloadDocument", "Controller")?filename=' + DocumentListName[i];
template = template + "<a href='" + url + "'>" + DocumentList[i] + "</a> ";
}
}
return template + "</ul>";
}
Related
My blog is 12 years old, I have more than 5000 posts. I am using a widget that shows random posts from a specific label. I set it to show 2 posts in the sidebar, and I noticed that these posts are always 'neighbors', which means they are always from the same month in the past. For example, it's always 2 posts from May 2014, or June 2018. It's never something like: 1 post from May 2014 and the other from June 2018. Do you have any idea what the problem is?
Here is the part of the code which (I believe) contains the mistake:
rand=Math.floor((Math.random()*_vRiO.total_entry)+1);
if(rand+bcd140526_post_count>_vRiO.total_entry){
rand=_vRiO.total_entry-bcd140526_post_count+1;
}
if(rand<1){
rand=1;
}
var _vXsM=HOST+_s7IgU[159];
if(bcd140526_index_label){
_vXsM+=_s7IgU[160]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[161]+bcd140526_post_count+_s7IgU[162]+rand+_s7IgU[163];
_fIoT(_vXsM);
}else{
_fYbP(json);
}
}
var _vXsM=HOST+_s7IgU[164];
if(bcd140526_index_label){
_vXsM+=_s7IgU[165]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[166];
if(bcd140526_sort_by==_s7IgU[167]){
_vXsM+=_s7IgU[168];
}else{
_vXsM+=_s7IgU[169]+bcd140526_post_count;
}
_vXsM+=_s7IgU[170];_fIoT(_vXsM);
I can't paste the whole code, the website doesn't let me. But you can get it here: https://sneeit.com/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget/
My settings:
Post Count - 2
Post Order - Random
Specific Label - Summer
Show Thumbnail - Checked
Thumbnail Size - 200
Show Label - No
Show Comment Numbers - No
Show Date - No
Show Author Name - No
Show Readmore - No
Show Snippet - No
Show Copyright - No
Design Style - List
I have painstakingly deobfuscated this extension to be able to check how you could modify it (which should be much easier for you if you still want to), and I see that getting "non-neighbor" random numbers is not what this system is designed to do. choosePost(json) chooses one post by number to be the starting post, and makeWidget (which, bizarrely, uses string concatenation and document.write to generate the widget) just uses the first post_count posts after the chosen post, so your objective is not (easily) doable.
var show_thumbnail = true;
var show_label = false;
var show_comment_numbers = false;
var show_date = false;
var show_author_name = false;
var show_readmore = false;
var show_snippet = false;
var hide_copyright = true;
var snippet_length = 150;
var post_count = 3;
var thumbnail_size = 140; // v1.5, only effect with list style
var sort_by = 'random'; // latest or random
var index_label = 'summer';
var design_style = 'list'; // list or column
var date_format = 'mm/dd/yyyy';
var lang_readmore = 'Readmore';
var HOST = '';
function sourceJSfile(url) {
document.write('<script type="text/javascript" src="' + url + '"<\/script>');
}
function generateDate(pub_date, format) {
pub_date = pub_date.split('-');
date = new Date(pub_date[0], pub_date[1] - 1, pub_date[2].substring(0, 2));
dd = date.getDate();
mm = date.getMonth() + 1;
yyyy = date.getFullYear();
format = format.replace('dd', dd);
format = format.replace('mm', mm);
format = format.replace('yyyy', yyyy);
return format;
}
function cleanContent(content) {
var tgt = '';
var imgtag = '<img ';
var srctag = 'src="';
var quote = '\"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
index2 = content.indexOf(quote, index1 + srctag.length);
tgt = content.substring(index1 + srctag.length, index2);
}
if (tgt == '') {
imgtag = 'data-thumbnail-src="';
srctag = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0 + imgtag.length);
if (index0 != -1) {
tgt = content.substring(index0 + imgtag.length, index1);
}
}
}
if (tgt == '') {
imgtag = '<iframe ';
srctag = 'src="';
quote = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
if (index0 != -1) {
index2 = content.indexOf(quote, index1 + srctag.length);
if (index0 != -1) {
tgt = content.substring(index1 + srctag.length, index2);
tgt = tgt.replace("http://www.youtube.com/watch?v=", '');
tgt = tgt.replace("http://www.youtube.com/embed/", '');
tgt = tgt.replace('?rel=0', '');
tgt = 'http://img.youtube.com/vi/' + tgt + '/mqdefault.jpg';
}
}
}
}
return tgt;
}
function jsonProcessor(json) {
var data = new Object();
var regex = /<\S[^>]*>/g;
data.id = json.feed.id.$t;
key = 'blog-';
index = data.id.indexOf(key);
data.id = data.id.substring(index + key.length);
data.id = data.id.replace('.comments', '');
data.cate = new Array();
if ('category' in json.feed) {
for (let i = 0; i < json.feed.category.length; i++) {
data.cate[i] = json.feed.category[i].term;
}
}
data.title = '';
if ('title' in json.feed) {
data.title = json.feed.title.$t;
}
data.subtitle = '';
if ('subtitle' in json.feed) {
data.subtitle = json.feed.subtitle.$t;
}
data.admin = new Object();
data.admin.name = 'Anonymous';
data.admin.uri = '';
data.admin.avatar = 'http://img1.blogblog.com/img/anon36.png';
if ('name' in json.feed.author[0]) {
data.admin.name = json.feed.author[0].name.$t;
}
if ('uri' in json.feed.author[0]) {
data.admin.uri = json.feed.author[0].uri.$t;
}
if ('gd$image' in json.feed.author[0]) {
if (json.feed.author[0].gd$image.src != 'http://img1.blogblog.com/img/blank.gif') {
data.admin.avatar = json.feed.author[0].gd$image.src;
}
}
data.total_entry = Number(json.feed.openSearch$totalResults.$t);
data.start_index = Number(json.feed.openSearch$startIndex.$t);
data.item_per_page = Number(json.feed.openSearch$itemsPerPage.$t);
data.entry_number = 0;
if ('entry' in json.feed) {
data.entry_number = json.feed.entry.length;
}
data.entry = new Array();
for (let i = 0; i < data.entry_number; i++) {
data.entry[i] = new Object();
temp = new Object();
entry = json.feed.entry[i];
temp.id = entry.id.$t;
key = 'post-';
index = temp.id.indexOf(key);
temp.id = temp.id.substring(index + key.length);
temp.published = '';
if ('published' in entry) {
temp.published = entry.published.$t;
}
temp.cate = new Array();
if ('category' in entry) {
for (j = 0; j < entry.category.length; j++) {
temp.cate[j] = entry.category[j].term;
}
}
temp.title = '';
if ('title' in entry) {
temp.title = entry.title.$t;
}
temp.content = '';
if ('content' in entry) {
temp.content = entry.content.$t;
}
temp.summary = '';
if ('summary' in entry) {
temp.summary = entry.summary.$t;
}
if (temp.summary == '') {
temp.summary = temp.content.replace(regex, '');
}
if (temp.content == '') {
temp.content = temp.summary;
}
temp.link = '';
temp.reply_label = 'comments';
if ('link' in entry) {
for (j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
temp.link = entry.link[j].href;
}
if (entry.link[j].rel == 'replies') {
temp.reply_label = entry.link[j].title;
}
}
}
temp.author = new Object();
temp.author.name = 'Anonymous';
temp.author.uri = '';
temp.author.avatar = 'http://img1.blogblog.com/img/anon36.png';
a0 = entry.author[0];
if ('name' in a0) {
temp.author.name = a0.name.$t;
}
if ('uri' in a0) {
temp.author.uri = a0.uri.$t;
}
if ('gd$image' in a0) {
if (a0.gd$image.src != 'http://img1.blogblog.com/blank.gif') {
temp.author.avatar = a0.gd$image.src;
}
}
temp.thumbnail = '';
if ('media$thumbnail' in entry) {
temp.thumbnail = entry.media$thumbnail.url;
}
temp.reply_number = 0;
if ('thr$total' in entry) {
temp.reply_number = Number(entry.thr$total.$t);
}
temp.reply_label = temp.reply_label.replace(temp.reply_number + ' ', '');
temp.reply_to = '';
temp.reply_json = '';
temp.reply_title = '';
if ('thr$in-reply-to' in entry) {
temp.reply_to = entry['thr$in-reply-to'].href;
temp.reply_json = entry['thr$in-reply-to'].source;
temp.reply_json = temp.reply_json.replace('/default/', '/summary/');
temp.reply_json = temp.reply_json + '?alt=json-in-script';
}
temp.pid = '';
if ('gd$extendedProperty' in entry) {
for (j = 0; j < entry.gd$extendedProperty.length; j++) {
if (entry.gd$extendedProperty[j].name == 'blogger.itemClass') {
temp.pid = entry.gd$extendedProperty[j].value;
}
}
}
temp.pid = temp.pid.replace('pid-', '');
data.entry[i] = temp;
}
return data;
}
if (typeof(jquery_included) == 'undefined') {
jquery_included = false;
}
function jqueryLoader() {
if (typeof(jQuery) == 'undefined') {
if (!jquery_included) {
jquery_included = true;
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js');
scriptEl.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
setTimeout(jqueryLoader, 50);
} else {
if (!($('link[href*="font-awesome.css"]').length)) {
linkEl = document.createElement('link');
linkEl.setAttribute('href', 'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
linkEl.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkEl);
}
}
}
jqueryLoader();
function makeWidget(json) {
var div = '<div style="clear:both!important;float:none;!important;line-height:0!important"></div>';
var jsonOut = jsonProcessor(json);
var docAppend = '';
if (jsonOut.total_entry) {
docAppend += ('<div class="post_feed ' + design_style + ' ' + ((show_thumbnail) ? 'thumb' : 'no-thumb') + '"><ul>');
for (let i = 0; i < jsonOut.total_entry && i < post_count; i++) {
p = jsonOut.entry[i];
docAppend += ('<li class="item item-' + i + '">');
if (!p.thumbnail) {
p.thumbnail = cleanContent(p.content);
}
if (show_thumbnail && p.thumbnail) {
var tgt = p.thumbnail;
if (tgt.indexOf('/s72-c/') != -1){
if (design_style === 'column')
tgt = tgt.replace('/s72-c/', '/s1600/');
else
tgt = tgt.replace('/s72-c/', '/s' + thumbnail_size + '-c/');
} else if (tgt.indexOf('youtube.com') != -1 && tgt.indexOf('/default.') != -1) {
tgt = tgt.replace('/default.', '/mqdefault.');
}
p.thumbnail = tgt;
docAppend += ('<a class="thumbnail" style="width:' + thumbnail_size + 'px;height:' + thumbnail_size + 'px;" href="' + p.link + '"><img src="' + p.thumbnail + '"/></a>');
}
docAppend += '<div class="item-body">';
if (show_label && (typeof(p.cate[0]) != 'undefined')) {
docAppend += ('<a class="cate" href="' + HOST + '/search/label/' + p.cate[0] + '">' + p.cate[0] + '</a>');
}
docAppend += ('<h3 class="title">' + p.title + '</h3>');
if (show_author_name || show_comment_numbers || show_date) {
docAppend += '<div class="meta">';
if (show_author_name) {
docAppend += ('<span class="meta-item author-name"><i class="fa fa-user"></i> ' + p.author.name + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item comment-number"><i class="fa fa-comment"></i> ' + p.reply_number + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item date-time"><i class="fa fa-clock-o"></i> ' + generateDate(p.published, date_format) +'</span>');
}
docAppend += (div + '</div>' + div);
}
if (show_snippet) {
if (p.summary.length > snippet_length) {
p.summary = p.summary.substring(0, snippet_length) + '...';
}
if (show_readmore) {
p.summary += ' ' + lang_readmore + '';
}
docAppend += ('<p class="snippet">' + p.summary + '</p>');
}
docAppend += (div + '</div>' + div);
docAppend += ('</li>');
}
docAppend += ('</ul>');
if (!hide_copyright) {
docAppend += div;
docAppend += '<a target="_blank" class="copyright" href="http://www.sneeit.com/2014/05/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget" style="font-size: 11px!important;text-align:right;visibility: visible;!important;text-indent:0!important;height:auto!important;width:100%!important;position:static!important;color:#999!important;display:block!important;opacity:1!important;">BloggerWidget</a>';
}
docAppend += ('</div>' + div);
} else {
docAppend += '<p><em>Have no posts</em><p>';
}
document.write(docAppend);
}
function choosePost(json) {
if (sort_by == 'random') {
var processedJSON = jsonProcessor(json);
rand = Math.floor((Math.random() * processedJSON.total_entry) + 1);
if (rand + post_count > processedJSON.total_entry) {
rand = processedJSON.total_entry - post_count + 1;
}
if (rand < 1) {
rand = 1;
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script&max-result=' + post_count + '&start-index=' + rand + '&callback=makeWidget';
sourceJSfile(request);
} else {
makeWidget(json);
}
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script';
if (sort_by == 'random') {
request += '&max-results=0';
} else {
request += '&max-results=' + post_count;
}
request += '&callback=choosePost';
sourceJSfile(request);
The modifications will take some work, but the deobfuscated version should be much easier to use. I'd recommend removing jqueryLoader, and to get you started: the API requests are sourceJSfile('/feeds/post/default/-/summer?alt=json-in-script&max-results=1&callback=choosePost'). You'd probably be better off rewriting the thing from scratch than trying to bodge it on top of this code, I think.
PS: This code loads the entire jquery library so it can load some random stylesheet in jqueryLoad.
i make custom mvc control with two kendo datepicker to display (gregi and hijri) date in partial view and if i change date of any one it's change the other to equivalent date
cause to kendo limitation to deal with Hijri calender i make some modification to display correct date i use culture and set max date to hijri to 29/12/1600
every thing is ok if i set value(DateTime.Now) to hijri calender
but i want it display null and user select value but if i remove value and when user open calender the year show is 1600 i want to display 1435 and keep value null
her is my code
Controller
public class UserControl_GHDate
{
public DateTime? GregiDate { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime? HijriDate
{
get
{
if (GregiDate==null)
{
return null;//DateTime.Now;
}
else
{
return GregiDate;
}
}
set { }
}
}
Razor
#model MVC_ERP.Models.UserControl_GHDate
<script src="#Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.ar-SA.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.en-US.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/kendo/cultures/kendo.culture.ar-SA.min.js")"></script>
#Html.Kendo().DatePickerFor(model => model.GregiDate).Format("dd/MM/yyyy").Culture("en-US").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("GregiChange"))
#Html.Kendo().DatePickerFor(model => model.HijriDate).Value(DateTime.Now).Footer(false).Max("12/29/1600").Culture("ar-SA").Min(new DateTime(1300, 1, 1)).Format("dd/MM/yyyy").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("HijriChange"))
<script>
kendo.cultures["ar-SA"].calendars.standard.firstDay =5;
//kendo.cultures["ar-SA"].calendars.standard.months.namesAbbr[0] = "bbb"; //change name of month
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[0] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[1] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[2] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[3] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[4] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[5] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[6] = "";
function GregiChange(e) {
//alert(this.Name())
var GregId = this.element.prop("id");
var arr = GregId.split('_');
var HijId = arr[0] + '_HijriDate';
if ($('#' + GregId).data('kendoDatePicker').value() == null)
{
$('#' + HijId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + GregId).data('kendoDatePicker').value())
//d.setMonth(d.getMonth() + 1);
var j = d.toLocaleDateString("en-US")
//var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian("1434", "02", "11");
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.fromGregorian(d);
var y = z.toString()
var arrD = y.split(',');
var year = arrD[0]
var month =(arrD[1]==0?1:(eval(arrD[1])+1))
var day = arrD[2]
var dat = day + '/' + month + '/' + year
$('#' + HijId).data('kendoDatePicker').value(dat)
}
function HijriChange() {
var HijId = this.element.prop("id");
var arr = HijId.split('_');
var GregId = arr[0] + '_GregiDate';
if ($('#' + HijId).data('kendoDatePicker').value() == null) {
$('#' + GregId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + HijId).data('kendoDatePicker').value())
var HD = d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
HDMY= d.getDate() + '/' + (d.getMonth()+1)
if (d.getDate() == 31 || HDMY == '30/12' || HDMY == '30/10' || HDMY == '30/8' || HDMY == '30/6' || HDMY == '30/4' || HDMY == '30/2')
{
alert(HD + ' not valid hijri date')
return;
}
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian(d.getFullYear(), (d.getMonth() + 1), d.getDate());
var u = new Date(z)
var year = u.getFullYear();
var month = (u.getMonth() == 0 ? 12 : u.getMonth());
var day = u.getDate()+1;
var dat = day+ '/' + month+ '/' + year;
$('#' + GregId).data('kendoDatePicker').value(dat)
}
$(".k-datepicker input").val('');
</script>
Thanks
I think kendo date picker has a min value option try specify the min value with a year of 1435
I would like to select the XPath of a tag and the content of the tag, something similar to what Evernote is doing. However, I cannot find any examples. How could this be achieved?
After some research we found this:
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
{
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[#id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[#class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++;
};
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
}
function lookupElementByXPath(path) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}
I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});